Andy
Andy

Reputation: 3522

How do I handle passwords and dockerfiles?

I've created an image for docker which hosts a postgresql server. In the dockerfile, the environment variable 'USER', and I pass a constant password into the a run of psql:

USER postgres
RUN /etc/init.d/postgresql start && psql --command "CREATE USER docker WITH SUPERUSER PASSWORD 'docker';" && createdb -O docker docker

Ideally either before or after calling 'docker run' on this image, I'd like the caller to have to input these details into the command line, so that I don't have to store them anywhere.

I'm not really sure how to go about this. Does docker have any support for reading stdin into an environment variable? Or perhaps there's a better way of handling this all together?

Upvotes: 0

Views: 5410

Answers (2)

helmbert
helmbert

Reputation: 38014

At build time

You can use build arguments in your Dockerfile:

ARG password=defaultPassword
USER postgres
RUN /etc/init.d/postgresql start && psql --command "CREATE USER docker WITH SUPERUSER PASSWORD '$password';" && createdb -O docker docker

Then build with:

$ docker build --build-arg password=superSecretPassword .

At run time

For setting the password at runtime, you can use an environment variable (ENV) that you can evaluate in an entrypoint script (ENTRYPOINT):

ENV PASSWORD=defaultPassword
ADD entrypoint.sh /docker-entrypoint.sh
USER postgres
ENTRYPOINT /docker-entrypoint.sh
CMD ["postgres"]

Within the entrypoint script, you can then create a new user with the given password as soon as the container starts:

pg_ctl -D /var/lib/postgresql/data \
       -o "-c listen_addresses='localhost'" \
       -w start
psql --command "CREATE USER docker WITH SUPERUSER PASSWORD '$password';"
postgres pg_ctl -D /var/lib/postgresql/data -m fast -w stop
exec $@

You can also have a look at the Dockerfile and entrypoint script of the official postgres image, from which I've borrowed most of the code in this answer.

A note on security

Storing secrets like passwords in environment variables (both build and run time) is not incredibly secure (unfortunately, to my knowledge, Docker does not really offer any better solution for this, right now). An interesting discussion on this topic can be found in this question.

Upvotes: 2

Daniel Stefaniuk
Daniel Stefaniuk

Reputation: 5764

You could use environment variable in your Dockerfile and override the default value when you call docker run using -e or --env argument.

Also you will need to amend the init script to run psql command on startup referenced by the CMD instruction.

Upvotes: 0

Related Questions