1. Understand the Compose model
Compose describes services, networks, volumes and configuration in a YAML file. Containers in the default Compose network can reach each other using service names. Published ports expose selected container ports on the host.
db:5432,不应把容器 IP 写死在配置里。2. Create a project directory
mkdir -p ~/compose-demo cd ~/compose-demo
3. Write a Compose file
cat > compose.yaml <<'YAML'
services:
web:
image: nginx:stable
ports:
- "127.0.0.1:8080:80"
restart: unless-stopped
YAMLThis example binds the web service to loopback only, so it is reachable from the host but not directly exposed on every public interface. Put a reverse proxy in front if public access is required.
4. Validate and start
docker compose config docker compose up -d docker compose ps curl -I http://127.0.0.1:8080
docker compose config renders the resolved configuration. Review it before starting, especially when environment variables or multiple Compose files are involved.
5. Inspect logs and processes
docker compose logs --tail=100 web docker compose logs -f web docker compose exec web nginx -t docker compose top
Press Ctrl+C to stop following logs; this does not stop the containers. Use exec for commands inside an already-running service.
6. Add persistent data only when needed
Containers are replaceable. Data that must survive container replacement belongs in a named volume or external storage. For example:
services:
app:
image: example/app:1.0
volumes:
- app-data:/var/lib/app
volumes:
app-data:Choose the actual image and data path from the application's documentation. Back up volumes using a method consistent with the application.
7. Lifecycle and cleanup
docker compose stop docker compose start docker compose pull docker compose up -d docker compose down
docker compose down -v removes declared named volumes. Do not use it as routine cleanup when volumes contain persistent data.8. Security essentials
- Pin reviewed image versions instead of relying on floating tags for critical production workloads.
- Do not bake secrets into images or commit
.envfiles. - Publish only required ports; bind internal services to loopback or private networks where appropriate.
- Run containers as non-root when the image supports it.
- Patch images and test upgrades before production rollout.
Checklist
- Validate the resolved Compose configuration.
- Understand port bindings and network reachability.
- Persist important data outside the container layer.
- Review logs and health after deployment.
- Protect secrets and test restore procedures.
References & further reading
Commands are examples for a representative Ubuntu/Linux environment. Review paths, versions, access requirements and maintenance impact before applying them to production systems.