2

The Docker Postgres samples library provides examples of starting a postgreSQL instance via docker run or using docker-compose file, both are shown below respectively.

The docker run call is exposing the password in the command and the docker-compose file exposes the password which could be viewed on Github. I've learnt to never expose credentials in this way and always retrieve from the environment. Is there a right way to dockerize postgreSQL with security in mind? Or is this secure and my understanding is incorrect?

docker run example:

docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres

docker-compose example:

version: '3.1' 
services:
    db:
        image: postgres
        restart: always
        environment:
            POSTGRES_PASSWORD: example

3 Answers 3

5

Indeed, even if those systems are not exposed publicly it's better to not have any credentials visible in source control.

There is an easy way to circumvent listing those values by simply omitting the right part of the environment definition and only listing the variable name. This way you can set the password in your shell beforehand and docker or docker compose will use it.

environment:
  - POSTGRES_PASSWORD

And then running it via

POSTGRES_PASSWORD=pass docker-compose up -d

Additionally there is a concept of secrets which are a way to store credentials and allow access only to specified containers.

See more at docker secrets

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

Comments

2

To add to the accepted answer, it's worth noting that as long as you have specified the environment variable in the docker-compose.yml file:

environment: 
  - POSTGRES_PASSWORD

and the current shell environment has the POSTGRES_PASSWORD already set, the following docker-compose command will inherit the POSTGRES_PASSWORD environment variable:

docker-compose up -d 

No need to prefix it to the docker-compose up -d command.

Comments

0

A trick would be to leave a literally .env file on the server where you're deploying which only contains the secrets.

Inside that file you can have to the effect of:

POSTGRES_PASSWORD=password
etc.

Moreover:

By default, the docker-compose command will look for a file named .env in the project directory (parent folder of your Compose file).

But I wouldn't rely on that, I would explicitly add the environment directive in the docker-compose to make it clear that external environmental variables are loaded.

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.