1

I'm using docker and dockerfile to build images. I want to build a PostgreSQL image so I'm using this dockerfile:

ARG POSTGRES_USER=vetouz
ARG POSTGRES_PASSWORD=***
ARG POSTGRES_DB=vetouz_mediatheque

FROM postgres:latest

USER postgres

EXPOSE 5432

Then I run the image using this command

docker run -e POSTGRES_PASSWORD=vetouz -d --name postgres postgres:latest

When I do that the role vetouz, the password and the db vetouz_mediatheque are not created and I don't understand why. I know it because when I access my container with sudo docker exec -it postgres bash and then run psql -U vetouz I get the error role vetouz does not exist.

It works if I run my image with the following command:

docker run -e POSTGRES_PASSWORD=*** -e POSTGRES_USER=vetouz -e POSTGRES_DB=vetouz_mediatheque -d --name postgres postgres:latest

But I would rather define my variables in the dockerfile.

Any idea why it's not working?

2 Answers 2

2

Please use ENV instead of ARG. args are only available during build, envs are available during runtime as well.

Source

Sign up to request clarification or add additional context in comments.

Comments

1

YOUR PROBLEM

As already stated your are using ARG that is only available when building the Docker image, but using env variables to set sensitive information in a Docker image is not a safe approach, and I will explain why.

SECURITY CONCERNS

But I would rather define my variables in the dockerfile.

This is ok for information that is not sensitive, but not a best practice for sensitive information like passwords, because the database credentials will be stored in plain text in the Dockerfile, and even if you use ARG to set the ENV var they will be available in the docker image layers.

docker run -e POSTGRES_PASSWORD=*** -e POSTGRES_USER=vetouz -e POSTGRES_DB=vetouz_mediatheque -d --name postgres postgres:latest

This is also a bad practice in terms of security because now your database credentials are saved into the bash history.

In a Linux machine you can check with:

history | grep -i POSTGRES

A MORE SECURE APPROACH

Create an .env file:
POSTGRES_USER=vetouz
POSTGRES_PASSWORD=your-password-here
POSTGRES_DB=vetouz_mediatheque

Don't forget to add the .env file to .gitignore:

echo ".env" >> .gitignore

Running the Docker Container

Now run the docker container with:

docker run --env-file ./.env -d --name postgres postgres:latest

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.