How to make Docker images more secure

Nowadays many of us work in daily basis with Docker, and we create our own Docker images with Dockerfile. However, do you know how to make Docker images more secure?

When we are writing our Dockerfile, Docker is using by default the root user to run the commands declared to create every layer in our image. Also, other times he copy and paste other Dockerfile templates which implicitly are using the root user by declaring this line:

USER root

Even this is redundant because Docker already uses it as default is not a good practice to keep that user. Instead, we should have our own user created for our specific purpose with only the needed permissions.

Why this is not a good practice

Even the Docker containers have certain level of isolation, we cannot forget Docker containers are still sharing the same kernel with the host, so using the root user in the wrong hands could end in a disaster.

The root user is not intended for ordinary tasks and should not be used for running our apps.

How to make Docker images more secure

The best practice to follow is to create a new user and a new group for our service, and assignt to it the right permissions at system level.

In order to create the user, we can run the following layers on our Dockerfile:

# Create a custom user with UID 1234 and GID 1234
RUN groupadd -g 1234 customgroup && \
    useradd -m -u 1234 -g customgroup customuser
 
# Switch to the custom user
USER customuser

Did you like this post? Don’t forget to read other related posts, leave your comment and ask for more content!


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top