Docker Fundamentals

Lesson 4 of 6

Volumes and Environment Variables

Containers are meant to be disposable, when one is removed, anything written to its filesystem is gone too. Volumes and environment variables are how you deal with data and configuration that need to survive or vary between environments.

Volumes: persisting data

docker run -d -p 27017:27017 -v mongo_data:/data/db mongo

-v mongo_data:/data/db mounts a named volume called mongo_data at /data/db inside the container. MongoDB's actual data lives in that volume, on the host machine, so it survives even if the container is removed and recreated.

Environment variables: configuration

docker run -e DATABASE_URL="postgresql://user:pass@db:5432/app" -p 3000:3000 my-app

-e passes an environment variable into the container, exactly like setting one in your shell, letting the same image behave differently across dev, staging, and production without being rebuilt.

TIP

Never bake secrets (passwords, API keys) directly into an image with COPY or RUN, pass them in at runtime with -e or an env file instead.

📝 Volumes & Env Vars Quiz

Passing score: 70%
  1. 1.Why use a volume instead of writing data directly into a container?

  2. 2.The ____ flag passes an environment variable into a running container.

  3. 3.Secrets like passwords should be baked directly into a Docker image with COPY.