Docker Dotenv

Today, I was preparing a Docker container for production release and found managing environment variables was a bit of a pain. As a ruby developer it's natural to me to use 12factor methodology for my environment so I wanted to use that with Docker.

EDIT: After I figured out my obscene way of doing it, I thought to check the docker helper page and sure enough, support is backed right in. You can simply pass in the location of the file using docker run --env-file=.env. That being said, I'm still publishing this to share what I learned about the shell and to serve as a reminder that I should always check the documentation more thoroughly.

Most tutorials described using docker-compose, but I'm deliberately not using that as I only want a single service. I'm also trying to learn as much about native Docker as possible before adding abstractions. After a few iterations I came up with the following shell command which I then put into a Makefile for easy re-use:

docker run `<.env xargs -I % echo "-e %"`

What that above code is doing is:

  • Reading the file .env (I previously used cat .env |)
  • Iterating over each line and pass it to xargs
  • xargs then outputs -e {LINE}

Using backslashes in-line with the Docker run command injects this concatenated string directly as if you were passing them yourself with multiple -e arguments.

There you have it, a highly overcomplicated way of passing a .env file to a Docker container. Although this isn't needed, I learned a lot about shell piping and concatenation using xargs.

Simplicity is prerequisite for reliability.

If you have any questions about this post, or anything else, you can get in touch on Twitter or browse my code on Github.