Use An .env File In Docker

Jeremiah Muchiri
Published: June 6, 2024

The short answer

In Docker, environment variables can be defined in a plain text file named .env, typically (but not necessarily) located in the root directory of your project, in the form of a list of key-value pairs:

Bash
VARIABLE=VALUE

Where:

  • VARIABLE is the name of the environment variable.
  • VALUE is the value assigned to that variable.

Once the .env file defined, you can start a new Docker container and load its variables into the container's environment using the docker run command with the --env-file flag as follows:

Bash
$ docker run --env-file <path> <image>

Where:

  • path is the path to the .env file.
  • image is the name of the base image the container will be launched from.

Note that since the .env file is supplied to the docker run command through the --env-file flag, it can be placed anywhere on the filesystem.

You can learn more about .env files in Compose by reading our other article on how to pass environment variables to services in Docker Compose.

The .env file syntax

To be valid, an .env file must follow a specific set of rules.

Variable names

Variable names must:

  • Have a maximum length of 64 characters.
  • Start with a letter (a-zA-Z]) or an underscore character (\_).

Variables can only contain:

  • Lowercase and uppercase letters (a-zA-Z]).
  • Numbers (1-9]).
  • Underscores (\_).

For example:

Bash
foobar
DATABASE_URL
_DB_HOST

Variable values

Values can:

  • Be empty.
  • Have a maximum length of 256 characters.
  • Optionally be enclosed in single quotes or double quotes.

For example:

Bash
PASSWORD=
USERNAME=johndoe
API_KEY='HelloWorld1234'
DATABASE_URL="http://localhost:5432"

Comments

Any line beginning with # will be treated as a comment and will therefore be ignored.

For example:

Bash
# This will be ignored
USERNAME=johndoe

Easily retrieve this syntax using Warp AI feature

If you’re using Warp as your terminal, you can easily retrieve this syntax using the Warp AI feature:

Entering How to create and load an .env file in Docker? in the AI question input will prompt a human-readable step by step guide including code snippets.

Using an.envfile per environment

To facilitate the development and deployment of software applications with Docker, it is common practice to store your environment variables into multiple .env files with an explicit name referencing the environment they are intended for.

For example:

  • .env.development
  • .env.staging
  • .env.production

This allows developers to easily manage and switch between configurations without altering the codebase, keep sensitive production credentials unexposed to testing environments, facilitate the software deployment through scripting, and prevent mistakes or unwanted changes in configuration.

For example:

Bash
$ docker run --env-file .env.development api-server-dev

Loading multiple.envfiles at once

In Docker, you can load several .env files at once, simply by repeating the --env-file flag multiple times:

Bash
$ docker run --env-file <path> [--env-file <path>] <image>

Note that if the same variable is defined multiple times in different .env files, its value will be overwritten by the value defined in the last specified .env file.

For example, let's consider the following .env files:

Bash
# .env.staging_1

DB_HOST="http://localhost:5432"
DB_USER="admin"
DB_PASSWORD="helloworld"
Bash
# .env.staging_2

DB_HOST="http://localhost:3306"

When launching the following container, the environment will contain all three variables DB\_HOST, DB\_USER, and DB\_PASSWORD, however, the DB\_HOST variable will hold the string "http://localhost:3306":

Bash
$ docker run --rm --env-file .env.staging_1 --env-file .env.staging_2 ubuntu env
DB_HOST="http://localhost:3306"
DB_USER="admin"
DB_PASSWORD="helloworld"

Unsupported features

Multi-line values

Docker doesn't currently support multi-line values and will only pick up on the first line.

For example, let's consider the following .env file:

Bash
PRIVATE_KEY="MIIBOgIBAAJBAKj34GkxFhD90vcNLYLInFEX6Ppy1tPf9Cnzj4p4WGeKLs1Pt8Qu
KUpRKfFLfRYC9AIKjbJTWit+CqvjWYzvQwECAwEAAQJAIJLixBy2qpFoS4DSmoEm"

When launching the following container, the PRIVATE\_KEY variable will only hold the first line of the value defined in the .env file:

Bash
$ docker run --rm --env-file .env ubuntu env | grep PRIVATE_KEY
PRIVATE_KEY="MIIBOgIBAAJBAKj34GkxFhD90vcNLYLInFEX6Ppy1tPf9Cnzj4p4WGeKLs1Pt8Qu

Inline comments

In Docker, a # appearing at the end of a value will be treated as part of the value.

For example, let's consider the following .env file:

Bash
DB_USER="admin" # comment

When launching the following container, the DB\_USER variable's value will also include the string # comment:

Bash
$ docker run --rm --env-file .env ubuntu env | grep DB_USER
DB_USER="admin" # comment

Interpolation

In Docker, the value of variables must be manually defined and cannot be copied from the local environment.

For example, let's consider the following .env file:

Bash
USERNAME=${USER}

When launching the following container, the USERNAME variable's value will be defined as the literal string "${USER}" and not the value contained in the USER.inline-code] environment variable:

Bash
$ docker run --rm --env-file .env ubuntu env | grep USERNAME
USERNAME=${USER}
Written by
Jeremiah Muchiri
Filed under

Related articles


Learning Docker (The Easy Way) Using LazyDocker & Warp

A concise guide to learning Docker using Lazydocker. Highlights Docker’s benefits and takes advantage of Warp's AI features for a quick setup.

Run SSH In Docker

Learn how to launch and connect to a containerized SSH server in Docker using password-based authentication and SSH keys.

Remove a Docker Image

Learn how to remove a Docker image locally, on a Docker registry, and on Artifactory.

Override the Container Entrypoint With docker run

Learn how to override and customize the entrypoint of a Docker container using the docker run command.

The Dockerfile ARG Instruction

Learn how to define and set build-time variables for Docker images using the ARG instruction and the --build-arg flag.

Start a Docker Container

Learn how to start a new Docker container from an image in both the foreground and the background using the docker-run command.

Stop All Docker Containers

How to gracefully shutdown running containers and forcefully kill unresponsive containers with signals in Docker using the docker-stop and docker-kill commands.

Set Docker Container Hostname

Learn how to set, change and match a docker container hostname.

How To Use An .env File In Docker Compose

Learn how define and pass environment variables to Docker containers using an .env file in Docker Compose.

Restart Docker Containers

Learn how to restart Docker containers automatically with restart policies and manually using the docker restart, docker start, docker stop and docker kill commands.

Run Bash Shell In Docker

Start an interactive shell in Docker container

Launch MySQL Using Docker Compose

Learn how to launch a MySQL container in Docker Compose.