How to Set Docker Environment Variables?

Posted on

How to Set Docker Environment Variables?

Docker is a powerful tool for creating consistent development environments. Environment variables are crucial for configuring applications within Docker containers.

This guide explores Docker environment variables and demonstrates how to set them using various methods: Docker CLI commands, Docker Compose, and within a Dockerfile. We’ll also cover best practices for managing these variables.

What are Docker Environment Variables?

Docker environment variables are predefined values that influence application behavior within a container. They are used for configuring applications, setting parameters for Docker images, and securely storing sensitive information like database credentials and API keys.

Environment variables enhance container portability and flexibility. By adjusting settings based on the deployment environment without rebuilding the image, applications can adapt to different environments at runtime. The container’s environment is defined explicitly in the service configuration.

How to Set Docker Environment Variables in Docker File?

A Dockerfile defines the steps to build a Docker image and allows you to define two types of variables:

ENV: Environment variables
ARG: Build-time variables

ENV Variables

Environment variables specified using ENV are applied to any container created from the image. The format for setting an environment variable in the Dockerfile is:

ENV env_variable_name=value

ARG Variables

Build-time variables are defined using ARG and can be passed at build time.

Here’s an example 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 environment variables. Use it like this:

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 the environment variables in a formatted JSON output. It’s useful for quickly checking what variables are configured within Docker instances.

2. Using docker exec Command

Another method to view environment variables is by using the docker exec command:

docker exec <containerID> env

Replace `<containerID>` with the ID of your running container. This command executes the `env` command inside the container, listing all currently set environment variables.

How to Set Docker Environment Variables Using Docker Compose?

Using the CLI to set environment variables at runtime isn’t ideal for multi-container applications. Use a docker-compose.yml file to define all environment variables. This file includes all configurations for the containers, applied with a single command when starting. To set environment variables using Docker Compose, explicitly define them in the service configuration.

Two methods can be used:

1. Using the `environment` Attribute

Define environment variables directly in the docker-compose.yml file using the `environment` attribute. For example, a Node application running with MongoDB:

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

Store environment variables in a separate .env file and reference it 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_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. It is recommended not to include this file in version control for security reasons.

This keeps variables separate from the configuration file, enhancing organization and security. By avoiding .env in the root directory, you can better manage sensitive information.

The env_file attribute also supports multiple .env files within a Compose application. Paths are relative to the docker-compose.yml file.

3. Set Docker Environment Variables with docker compose at the run time

Docker Compose allows setting environment variables using the command line with the `–env-file` option.

docker compose --env-file <environmental_variables_file> up

Add a new sample environment variable to the .env file.

MONGODB_PASSWORD=test

Run the application and view the configured environment variables.

4. Use Docker Compose to run set one-off Docker Environment Variables

When setting environment variables for a one-off container run using `docker compose run`, you can use the `-e` or `–env-file` options. This allows you to override or set variables for that specific container instance only.

For example, to modify the `DEBUG` variable in your web application container:

docker compose run -e DEBUG=0 web

This sets `DEBUG` to `0` specifically for the `web` service/container during this run, tailoring the environment.

What are the Best Practices for Setting Docker Environment Variables?

Follow these best practices to ensure security, consistency, and maintainability:

  • Use a .env File: Store variables in a separate .env file. This helps organize them across environments (development, testing, production). Add the .env file to .gitignore to prevent sensitive data from being committed.
  • Encrypt Sensitive Data: Avoid storing passwords and API keys directly in plain text. Use encryption and decrypt within the application when needed.
  • Avoid Runtime Changes: Avoid changing environment variables within a running container to ensure consistency. If changes are necessary, stop the container, make the changes, and start a new instance.
  • Use Standard Naming Conventions: Use a standard naming convention for environment variables to make them easier to manage and understand.
  • Regular Maintenance: Review and update environment variables regularly to ensure they are current and relevant. Remove or update outdated variables.

Conclusion

This guide covered the importance of Docker environment variables for consistent application behavior, how to define them in a Dockerfile, and how to adjust them using CLI commands and Docker Compose. By following best practices, you can securely manage sensitive data, ensure consistent configurations, and improve deployment efficiency.

BlueVPS.com offers high-performance VPS solutions with cloud-like availability, providing a scalable and customizable environment ideal for Docker deployments. Enjoy dedicated resources and unlimited traffic, optimizing your Dockerized applications for robust performance and seamless scalability.

Leave a Reply

Your email address will not be published. Required fields are marked *