How to Set Docker Environment Variables?
Docker is a versatile tool that ensures a uniform development environment across different platforms. Environment variables in Docker play an important role in configuring applications within a Docker container.
In this guide, you will explore the essential information about Docker environment variables. In addition, how to set docker environment variables using multiple methods, including setting or overriding them via Docker CLI commands and Docker Compose, along with some best practices to consider.
What are Docker Environment Variables?
Docker environment variables are predefined values that influence all applications inside a container. They serve various purposes, such as defining application behaviour, setting configuration parameters for Docker images, and securely storing sensitive information like database credentials and API keys.
These variables are important for improving the container's portability and flexibility. You can adjust settings based on the deployment environment without rebuilding the image by using environment variables. This allows configurations to be injected at runtime, ensuring the container can function in different environments and enhancing its overall portability. The container's environment is only set when explicitly defined in the service configuration.
How to Set Docker Environment Variables in Docker File?
A Dockerfile defines all the necessary steps to build a Docker image and allows you to define two types of variables:
ENV: Environment variablesENV Variables
ARG: Build-time variables
Environment variables specified using ENV are applied to any container created from the image. The format for setting an environment variable in the docker file is as follows:
ENV env_variable_name=value
ARG Variables
Build-time variables are defined using ARG and can be passed at build time.
Below is an example of a Dockerfile that uses environment variables:
# Use an official Node.js runtime as a parent image
FROM node:14
# Set environment variables
ENV NODE_ENV=production
ENV PORT=3000
# Set the working directory
WORKDIR /usr/src/app
# Copy package.json and package-lock.json
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy the rest of the application code
COPY . .
# Expose port 3000
EXPOSE 3000
# Run the app
CMD ["npm", "start"]
In this example, NODE_ENV and PORT are environment variables set using the ENV directive. These variables will be available to any container built from this Dockerfile.
Viewing Docker Environment Variables: Viewing and Managing Variables in Docker Container
To view Docker environment variables set within a Docker container or image, Docker provides several methods for debugging and inspection.
1. Using docker inspect Command
The docker inspect command allows you to examine detailed information about a container or image, including the docker environment variables. Here’s how you can use it:
docker inspect --format '{{.Config.Env}}' <containerId_or_imageId>
Replace <containerId_or_imageId> with the actual ID of your container or image. This command retrieves and displays only the docker environment variables (Env) in a formatted JSON output. It's useful for quickly checking what variables are currently configured within Docker instances.
2. Using docker exec Command
Another method to view the configured docker environment variables is by using the docker exec command. Here's how you can do it:
docker exec <containerID> env
Replace <containerID> with the ID of your running container. This command will execute the env command inside the specified container, listing all the environment variables currently set within it.
How to Set Docker Environment Variables Using Docker Compose?
Using the CLI to set Docker environment variables at runtime is not ideal for multi-container applications. A better approach is to use a docker-compose.yml file to define all environment variables. This file includes all the necessary configurations for the containers, and you can apply them with a single command when starting the containers. To set environment variables within a container using Docker Compose, you must explicitly define these variables in the service configuration.
There are two methods used to set docker environment variables using Docker Compose:
1. Using the environment Attribute
In this method, you directly define environment variables within the docker-compose.yml file using the environment attribute. For example, we have a node application running with the MongoDB database:
Docker compose file:
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
environment:
- PORT=3000
- MONGO_URI=mongodb://mongo:27017/database_name
depends_on:
- mongo
mongo:
image: mongo:4.4
ports:
- "27017:27017"
volumes:
- mongo-data:/data/db
volumes:
Mongo-data:
2. Using .env or env_file Attribute
In this method, you store docker environment variables in a separate .env file and reference this file in the docker-compose.yml file.
Here is the .env file:
PORT=3000
MONGO_URI=mongodb://mongo:27017/database_name
Docker compose file:
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
env_file:
- .env
depends_on:
- mongo
mongo:
image: mongo:4.4
ports:
- "27017:27017"
volumes:
- mongo-data:/data/db
volumes:
Mongo-data:
Using a .env file offers flexibility and convenience, allowing you to use the same file with the docker run --env-file ... command or share it across multiple services in Docker Compose without duplicating lengthy environment variable sections in your YAML configuration.
This approach keeps environment variables separate from the main configuration file, enhancing organization and security. By not placing the .env file directly in the root directory, you can better manage sensitive information.
The env_file attribute also supports the use of multiple .env files within a Compose application. The paths specified for these .env files in the env_file attribute are relative to the location of your docker-compose.yml file.
3. Set Docker Environment Variables with docker compose at the run time
Docker compose allows you to set docker environment variables using the command line with the --env-file option.
docker compose --env-file <environmental_variables_file> up
Now, add the new sample environmental variable to the .env file.
MONGODB_PASSWORD=test
Run the application and view the configured docker environment variables.
4. Use Docker Compose to run set one-off Docker Environment Variables
When using docker compose run to set environment variables for a one-off container run, you can specify these variables using the -e or --env-file options. This approach is similar to docker run and allows you to override or set environment variables for that specific container instance only.
For instance, to modify the DEBUG variable in your web application container, you would execute:
docker compose run -e DEBUG=0 web
This command sets the DEBUG variable to 0 specifically for the web service/container during this run, tailoring the environment to the immediate needs of that execution context.
What are the Best Practices for Setting Docker Environment Variables?
Setting Docker environment variables involves several best practices to ensure security, consistency, and maintainability:
- Use a .env File: Store environment variables in a separate .env file. This helps organize variables across different environments (development, testing, production). Ensure the .env file is added to .gitignore to prevent sensitive data from being committed to version control.
- Encrypt Sensitive Data: Avoid storing sensitive information such as passwords and API keys directly in plain text. Instead, use encryption to store them securely. Decrypt these variables within the application when needed.
- Avoid Runtime Changes: Do not change environment variables within a running container. This practice ensures consistency across different environments. If changes are necessary, stop the container, make the changes, and start a new instance.
- Use Standard Naming Conventions: Maintain consistency by using a standard naming convention for environment variables. This makes it easier to manage and understand their purpose.
- Regular Maintenance: Review and update docker environment variables regularly to ensure they are current and relevant. Remove or update outdated variables to maintain clarity and efficiency.
Conclusion
This guide covered the importance of Docker environment variables in maintaining consistent application behavior across different platforms. We discussed how to define these variables in a Dockerfile and adjust them using CLI commands and Docker Compose. By following best practices, you can securely manage sensitive data, ensure consistent configurations with a docker compose, and improve deployment efficiency.
BlueVPS.com offers high-performance VPS solutions combined with cloud-like availability, providing a simple, scalable, and customizable environment ideal for Docker deployments. Enjoy dedicated resources and unlimited traffic, optimizing your Dockerized applications for robust performance and seamless scalability.