Environment variables in Dockerfile and docker-compose

Overview
Environment variables are a simple and popular option to avoid hard-coding credentials into your code or build files, while eliminating the risk of accidentally pushing sensitive information to Git. Most importantly, utilizing them in your programs is very easy.
Say, you want to retrieve the username and password of your firewall in a Python program. This is all you have to do:
import os
fw_username = os.getenv('FW_USER')
fw_password = os.getenv('FW_PASS')
Recently, I had to dockerize an API server that I have developed. This API server needed to authenticate to multiple other services to function. We just observed how it is done inside the code but how do you use them in a Dockerfile to pass them to the program?
Let’s quickly explain what environment variables are before jumping right into the solution.
Environment Variables
An environment variable is a key-value item that can influence how programs behave on a computer. They keep information that the operating system and other programs need. For example the PATH environment variable that contains a list of directories where executable files are located.
Execute env command in your shell to get a list of all defined environment variables.
Defining a new environment variable is possible in different ways but I’ll cover three ways here:
- inline with a command you want to run:
LOG_LEVEL=debug ./my_program
We just defined a temporary environment variable here that only affects the my_program and goes out of scope when the my_program exits.
- Session wide:
export LOG_LEVEL=debug
./my_program
Using the export command, we defined an environment variable which will be available throughout the life of our terminal session. This way, other processes can also use that environment variable.
- Defining environment variables in files that are run on system startup or login sessions:
An example of these files on Linux would be .bashrc and .profile files. Appending your environment variables to them will load them when you spawn or login to a shell (e.g. Bash)
echo 'export LOG_LEVEL=debug' >> ~/.bashrc
# or
echo 'export LOG_LEVEL=debug' >> ~/.profile
Using Environment Variables in Dockerfile and docker-compose
Let’s write a simple Dockerfile to demonstrate a few things:
Write a Dockerfile
FROM python:3.11.1
ARG LOG_LEVEL=info
ENV LOG_LEVEL=${LOG_LEVEL}
RUN apt-get update -y \
&& apt-get install -y --no-install-recommends gcc g++ \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY ./requirements.txt /app/
COPY ./*.py /app/
RUN pip3 install --no-cache-dir -r /app/requirements.txt
CMD [ "python3", "main.py", "0.0.0.0", "8080"]
The important lines here are the ones starting with ARG and ENV.
- ARG: Defines a build-time variable that can be passed to the
docker buildcommand using the--build-argoption or throughdocker compose, more on that later. Here,LOG_LEVELdefaults toinfoif nothing is passed. - ENV: Sets an environment variable that is saved in the image and is available to the container at runtime. In this case, the
LOG_LEVELenvironment variable is set to the value of theLOG_LEVELbuild-time variable.
Never pass credentials through ARG or ENV. Their values are saved in the image, and anyone who has the image can read them with
docker historyordocker inspect. Pass them when the container starts instead, as shown in the next section.
Now, we can write out our docker-compose file to define how Docker containers should be run.
Write a docker-compose file
As mentioned earlier docker-compose files define how Docker containers are run and connected together. As of this writing, the provided example is the new docker-compose format (notice the lack of version key on top):
services:
api_server:
image: my_program:1.0
build:
context: .
dockerfile: Dockerfile
args:
- "LOG_LEVEL=debug"
environment:
- "FW_USER=${FW_USER}"
- "FW_PASS=${FW_PASS}"
container_name: "my_program"
volumes:
- ./:/app
proxy_server:
image: nginx:latest
container_name: nginx_proxy
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf
What matters for this post are these lines:
args:
- "LOG_LEVEL=debug"
environment:
- "FW_USER=${FW_USER}"
- "FW_PASS=${FW_PASS}"
Please note that my example is using the docker compose plugin and differs from the docker-compose command; although the outcome is the same regardless of the command used.
Here is what happens when you run docker compose build:
- docker compose passes
LOG_LEVEL=debugto theDockerfileas a build-time variable - Docker image gets built with
LOG_LEVELset todebug
And here is what happens when you run docker compose up:
- docker compose looks up
FW_USERandFW_PASSin the shell it is running on - They get passed to the container as environment variables when it starts
- The program reads them with
os.getenv, while the credentials never end up in the image
The
environmentkey only affects the running container. It does not pass anything to theDockerfileduring the build. That is what theargskey underbuildis for.
Conclusion
In this post, we discussed what environment variables are and how to use them in our programs and Dockerfiles.
Although this method is relatively safe and way better than hard-coding credentials in your programs, it is still not the best option out there.
Whenever possible, you should consider using identity and secret management solutions such as Hashicorp’s Vault.
environment variables docker dockerfile docker-compose linux devops security credential management
824 Words
2023-03-19 13:42