🐳 How to Pass Environment Variables in Docker Container with Docker Compose 🚀

🐳 How to Pass Environment Variables in Docker Container with Docker Compose 🚀

When running Docker containers with Docker Compose, it’s often necessary to pass environment variables to the containers. This is especially important for sensitive information, such as passwords or API keys, that you don’t want to hardcode in your Dockerfile.

Here’s an example of how to use Docker Compose to pass environment variables to a container:

version: '3'

services:
  myapp:
    build: .
    environment:
      - NODE_ENV=${NODE_ENV:-development}
      - DATABASE_URL=${DATABSE_URL}
    ports:
      - "3000:3000"

In this example, the myapp service is built from the current directory (which should contain a Dockerfile), and the environment section is used to define the environment variables that should be passed to the container. The values of these variables are read from the host system's environment variables, which can be defined in a .env file or passed in through the command line. The syntax NODE_ENV: ${NODE_ENV:-development} sets a default value of development if the NODE_ENV environment variable is not defined.

To define the values of these variables, create a .env file in the same directory as your docker-compose.yml file, with contents like:

NODE_ENV=production
DATABASE_URL=postgres://user:password@localhost/mydatabase

You can then use docker-compose up to start the container, and Docker Compose will automatically pass the environment variables to the container.

Here’s an example of a Dockerfile that sets up an application to receive environment variables:

FROM node:14

# Set environment variables
ARG NODE_ENV
ENV NODE_ENV=${NODE_ENV}

ARG DATABASE_URL
ENV DATABASE_URL=$DATABASE_URL

# Create app directory
WORKDIR /app

# Install app dependencies
COPY package*.json ./
RUN npm install

# Bundle app source
COPY . .

# Expose port and start the app
EXPOSE 8080
CMD [ "npm", "start" ]

In this example, we’re setting environment variables using the ENV instruction, which sets the values of these variables during the build process. These variables can be referenced later in the Dockerfile using the ${VARIABLE} syntax.

This is a great way to keep sensitive information out of your Dockerfile and ensure that your container is properly configured with the correct environment variables.

Happy Dockerizing! 🚢🐳💻

Did you find this article valuable?

Support Aashish Chakravarty by becoming a sponsor. Any amount is appreciated!