One file, two services
Compose is for running a small stack, not just one container. In this lesson, your stack has an app service built from your Dockerfile and a database service pulled from an image.
The app talks to the database by service name, like db. Compose creates the network for you.
What Compose adds
Your Dockerfile says how to build your app image. compose.yaml says which containers run together, which ports are published, and which volumes keep data.
Use docker compose, with a space. Older tutorials may show docker-compose with a hyphen. Treat that as old style.
Basic compose file
This example is for a Node app and Postgres. Change the app port, command, and database variables to match your project.
Current Compose examples start directly with services. You do not need a top-level version field.
services:
app:
build: .
ports:
- "127.0.0.1:3000:3000"
environment:
DATABASE_URL: "postgres://appuser:apppassword@db:5432/appdb"
depends_on:
- db
db:
image: postgres:16
environment:
POSTGRES_USER: appuser
POSTGRES_PASSWORD: apppassword
POSTGRES_DB: appdb
volumes:
- db_data:/var/lib/postgresql/data
volumes:
db_data:Run the stack
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
Publish the app only
ports publishes a container port to your laptop. expose only makes a port reachable to other services inside the Compose network.
For a local hackathon project, publish the app port. Do not publish the database port unless you really need to connect from a desktop database tool.
Do not expose publicly
A port like "3000:3000" binds to all interfaces. On a normal college laptop this is usually fine, but on a cloud VM with a public IP it can expose the app to the internet.
For local review, prefer "127.0.0.1:3000:3000". It binds the app to your own machine.
Keep database data
The db_data volume keeps Postgres files outside the database container. If the container is recreated, your local data can remain.
Reusable named volumes must also be declared at the bottom under volumes. That is why db_data appears in two places.
Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done