0
0
Dockerdevops~30 mins

Environment files (.env) in Docker - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Environment Files (.env) with Docker
📖 Scenario: You are creating a simple Docker container that needs to use environment variables for configuration. Instead of hardcoding these variables inside the Dockerfile or docker run command, you will use an environment file (.env) to keep your settings organized and easy to change.This is like writing down your secret recipe on a note instead of memorizing it every time you cook. It helps keep things clean and safe.
🎯 Goal: Build a Docker setup that reads environment variables from a .env file and uses them inside a container.You will create the .env file, configure Docker to use it, and then run a container that prints the environment variables.
📋 What You'll Learn
Create a .env file with specific environment variables
Write a simple Dockerfile that uses an environment variable
Configure Docker Compose to load the .env file
Run the container and display the environment variables
💡 Why This Matters
🌍 Real World
Environment files are used in real projects to keep configuration separate from code. This makes it easy to change settings without rebuilding images or changing code.
💼 Career
Knowing how to use <code>.env</code> files with Docker is a key skill for DevOps engineers and developers working with containerized applications.
Progress0 / 4 steps
1
Create the .env file with environment variables
Create a file named .env with these exact lines:
APP_NAME=MyApp
APP_PORT=8080
Docker
Need a hint?

Use a text editor to create a file named .env and add the two lines exactly as shown.

2
Write a simple Dockerfile that uses the environment variables
Create a Dockerfile with these exact lines:
FROM alpine
ENV APP_NAME=$APP_NAME
ENV APP_PORT=$APP_PORT
CMD ["sh", "-c", "echo Running $APP_NAME on port $APP_PORT"]
Docker
Need a hint?

Write a Dockerfile starting with FROM alpine. Use ENV to set APP_NAME and APP_PORT from the environment variables. Use CMD to print a message using these variables.

3
Create a docker-compose.yml file to load the .env file
Create a docker-compose.yml file with these exact contents:
version: '3.8'
services:
  app:
    build: .
    env_file:
      - .env
Docker
Need a hint?

Create a docker-compose.yml file that builds the current directory and loads the .env file using env_file.

4
Run the container and display the environment variables
Run docker-compose up --build in the terminal and observe the output. The container should print:
Running MyApp on port 8080
Docker
Need a hint?

Use the command docker-compose up --build to build and run the container. The output should show the message with the environment variables.