โWrite a docker-compose.yml that builds my app from the local Dockerfile, maps port 3000, and loads env vars from a .env file. Explain build vs image.โ
07 โ Write docker-compose.yml for local dev (app only)
Category: Docker Compose ยท Priority: High ยท Step: 8
Define the service, map ports, set env vars via a
.envfile. Usebuild: .to build from the local Dockerfile.
๐ฏ What is this task?
So far you've been running Docker with long docker run commands. Docker Compose lets you define everything in a single docker-compose.yml file and start it all with one command: docker compose up. This is how developers run apps locally in a real team.
๐ค AI Prompt
"Create a
docker-compose.ymlfile for a Node.js Express app. The service should be calledapp, build from the local Dockerfile, map port 3000, and read environment variables from a.envfile. Use Docker Compose v3.8 format. Add comments explaining each section."
๐ Step-by-step
Step 1 โ Create a .env file in your project root
This file holds your local environment variables. Never commit this to Git.
PORT=3000
NODE_ENV=development
Step 2 โ Create docker-compose.yml
version: "3.8"
services:
app:
# Build the image from the Dockerfile in the current folder
build: .
# Map port 3000 on your computer to port 3000 in the container
ports:
- "3000:3000"
# Load environment variables from the .env file
env_file:
- .env
# Restart the container automatically if it crashes
restart: unless-stopped
Step 3 โ Start the app
docker compose up
This builds the image (if not already built) and starts the container. You'll see logs directly in your terminal. To run it in the background:
docker compose up -d
Step 4 โ Check it works
Open http://localhost:3000 โ should respond.
Step 5 โ Useful Compose commands
docker compose up -d # Start in background
docker compose logs -f # Watch logs
docker compose down # Stop and remove containers
docker compose ps # See running containers
docker compose build # Rebuild the image
โ Done when
-
docker-compose.ymlexists in your project root -
.envfile exists (and is in.gitignore!) -
docker compose upstarts the app -
http://localhost:3000responds
๐ Quiz
Answer all 2 questions correctly to complete this lesson.