Skip to content

What Is Docker Compose? A Complete Guide to Running Multiple Containers from One File

A complete guide to Docker Compose: the structure of docker-compose.yml (services, ports, volumes and networks), the core commands, a practical multi-container example (web + database + cache), how services reach each other by name, persistent data and environment variables, and production tips from restart policies to health checks.

VPSيوسف الحربي28 min read
Illustration of an indented definition file producing three linked containers, representing running multiple containers from one file
On this page

Docker Compose is the natural bridge between "I ran a single container on my machine" and "I have a real application with several parts running on my server." No serious application today is a single container: it is a web application talking to a database, with a caching layer alongside, and perhaps a reverse proxy in front of them. Running these pieces by hand with separate commands is tiring and error-prone, and this is where Compose comes in, turning all of it into a single file you can read, review and share. If you haven't set up your server yet, start with the guide to setting up your first VPS, then come back here to run your applications elegantly with Compose.

What is Docker Compose, and what problem does it solve?

Let's start with the container itself. A container is a lightweight, isolated instance of an application with all its dependencies, running on top of Docker without booting a full operating system the way virtual machines do. Running a single container is easy: docker run, a few flags, and you're done. The problem starts when your application becomes more than one container, and that happens remarkably fast.

Picture a simple WordPress application: you need a container for the PHP server, a container for a MySQL database, and perhaps a Redis container for caching. Each container needs a shared network to talk to the others, volumes to store data, environment variables for passwords, and the correct boot order. If you wanted to do this with separate docker run commands, you would write three very long commands, create the network by hand, attach each container to it, set the flags precisely, and remember all of it every time you restart. The first typo in a single flag breaks everything, and there is no written "source of truth" to go back to.

Docker Compose solves exactly this. Instead of scattered commands, you write a single YAML text file that describes the desired state of your entire application: which services there are, which image each one uses, how they connect, and where they store their data. Then one command, docker compose up -d, reads the file and builds everything: it creates the network, starts the containers in order, attaches the volumes and applies the variables. Another single command, docker compose down, stops everything and cleans up. The file is plain text, so you put it in Git, review it in pull requests, and share it with your team or copy it to another server, where it works exactly the same way.

The core idea: Compose is not a new technology underneath containers but a declarative orchestration layer on top of Docker. You describe what you want, and Compose translates it into the Docker commands you would otherwise have written by hand. This shift from "imperative commands" to "declarative description" is what makes it an indispensable tool for anyone hosting real applications on their server.

It's worth pausing on what "declarative" means here, because it is the heart of the idea. In the imperative approach you give the computer a sequence of steps: create a network, then start this container, then attach it, then start that one. Any step you forget or put in the wrong order breaks the result, and you have to keep track of the current state every time. In the declarative approach you describe the destination ("I want these three services with these settings, connected like this") and leave it to Compose to get there. If you run up twice, Compose doesn't repeat the work; it compares reality with the description and fixes only the difference. This same idea, describing the desired state instead of the steps to reach it, is what all modern infrastructure tools are built on, and Compose is the simplest practical way into it.

One file runs multiple containers on a shared networkdocker-compose.ymlShared Compose network (bridge)webWeb server :8080dbDatabasecacheRedisEach service calls the others by name, not by IP, on the same network
A single docker-compose.yml file defines several services, and Compose runs them as containers on one shared network where each service calls the others by name (web → db → cache).

Why is Compose better than repeating docker run commands?

You might ask: if all Compose does is translate a description into Docker commands, why not write a Bash script that bundles the docker run commands and be done with it? The answer is that the difference isn't just the number of commands; it is clarity, maintenance and recovery. The following table compares the two approaches on the dimensions that matter in practice:

CriterionSeparate docker run commandsDocker Compose
Source of truthScattered across scripts and memoryOne clear file in Git
Starting the full stackSeveral commands in manual orderdocker compose up -d
Stopping and cleaning upStop and delete each container by handdocker compose down
Networking between containersCreated and attached by handAutomatic, by service name
Reviewing changesDifficult (no reference file)A clean diff in the pull request
Moving to another serverRewrite the commandsCopy the file and run it
Risk of human errorHigh (long flags)Low (structured description)

Notice that the biggest gain isn't the single line that starts everything, but the fact that the file becomes living documentation of your application's architecture. Any new developer who opens docker-compose.yml understands immediately: these are the three services, these are the images, these are the ports, this is the persistent data. There's no need to ask "How do we run this locally?" because the answer is written down. And when you need to move the application to another VPS or upgrade the database version, you change one line in the file and restart, instead of untangling a chain of interlocking commands.

There is also a less obvious benefit: Compose understands the relationships between services. When you state that the web service depends on db, Compose knows to start the database first. And when you update just one image, it recreates only that container and leaves the rest running. This orchestration intelligence is practically impossible with raw docker run scripts unless you write complex logic yourself.

How is a docker-compose.yml file structured?

The file is written in YAML, a format that relies on indentation to express nesting: no brackets and no semicolons, just two spaces per level. The top-level key is always services:, under it each service by name, and under each service its settings. Here is the simplest possible file, running a single web server:

yaml
services:
  web:
    image: nginx:latest
    ports:
      - "8080:80"

This file defines one service named web, which uses the nginx image and maps port 8080 on the server to port 80 inside the container. Notice that there is no version: key at the top; that is intentional and correct in the modern format. The following table explains the most important keys you'll use inside each service:

KeyWhat it doesExample
imageThe image the container is created frompostgres:16
buildBuild an image from a local Dockerfile instead of pulling onebuild: .
portsMap a server port to a container port"8080:80"
volumesAttach persistent storage or a folder to the containerdb-data:/var/lib/postgresql/data
environmentEnvironment variables inside the containerPOSTGRES_PASSWORD: secret
env_fileLoad variables from a .env fileenv_file: .env
depends_onStartup order between servicesdepends_on: [db]
restartRestart policy on failureunless-stopped
networksThe networks the service joinsnetworks: [backend]
healthcheckA periodic health check of the containerA command + an interval

Understanding the ports syntax matters: in the value "8080:80", the number on the left is the port on the server (exposed to the outside) and the number on the right is the port inside the container. If you don't need to expose a port to the world, as with a database, don't add ports at all: services reach each other internally without any exposed port, and that is more secure, as we'll see. volumes attaches storage that survives deleting the container, environment passes settings and secrets, and depends_on controls the order.

What are the core Docker Compose commands?

Once the file is written, you manage your application's lifecycle with a small set of commands run from inside the folder that contains docker-compose.yml. You'll usually run these commands on your server over SSH, so if you're not used to it, read SSH basics for beginners first. The following table collects the commands you'll use every day:

CommandWhat it does
docker compose up -dBuilds and starts all services in the background (detached)
docker compose downStops and removes the containers and network (not volumes, by default)
docker compose psShows the status of running services and their ports
docker compose logs -fFollows the logs of all services in real time
docker compose logs -f webFollows the logs of a single service only
docker compose exec web shOpens a shell inside a running container
docker compose pullPulls the latest versions of the defined images
docker compose restartRestarts services without recreating them
docker compose stopStops containers without removing them
docker compose configValidates the file and prints the final result

The -d flag in up -d means "detached": it runs in the background and gives you back the terminal instead of tying it up with logs, which is always what you want on a server. The logs -f (follow) command is invaluable for diagnosis: it shows you what the application prints moment by moment, and you can narrow it to a single service by adding its name. exec takes you inside a running container to inspect a file or run a command; for example, docker compose exec db psql -U postgres opens the database client directly.

Note a subtle but important difference: docker compose down removes the containers and the network, but it does not remove named volumes by default, so your data is safe. If you add the -v flag (that is, down -v), it removes the volumes too and the data is lost. Use it with great care and never run it in production unless you're sure. For a clean upgrade, docker compose pull followed by docker compose up -d fetches the new images and recreates only the affected containers, without touching the rest.

A practical example: a web app, database and cache stack

Enough theory; let's build a real file. We'll run a very common stack: a web application that relies on a PostgreSQL database and a Redis caching layer. This pattern applies to most modern applications, from Node.js APIs to Python and PHP applications. Here is the complete file:

yaml
services:
  web:
    image: myapp:latest
    restart: unless-stopped
    ports:
      - "8080:8080"
    environment:
      DATABASE_URL: "postgres://app:${DB_PASSWORD}@db:5432/appdb"
      REDIS_URL: "redis://cache:6379"
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_started

  db:
    image: postgres:16
    restart: unless-stopped
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_DB: appdb
    volumes:
      - db-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app"]
      interval: 10s
      timeout: 5s
      retries: 5

  cache:
    image: redis:7
    restart: unless-stopped
    volumes:
      - cache-data:/data

volumes:
  db-data:
  cache-data:

Let's read this file line by line. Under services: there are three services: web, db and cache. The web service is the only one that exposes a port to the world (8080:8080), because it is the front end that users reach. Notice its environment variables: DATABASE_URL points to the host db, which is the service name itself, not an IP address, and REDIS_URL points to cache. This is the essence of Compose networking, which we'll detail shortly.

The db service doesn't expose any port to the outside (no ports key), and that is intentional and secure: the database should be visible only to the web service over the internal network, not to the internet. It stores its data in a named volume, db-data, attached to the path where PostgreSQL keeps its files, so the data survives even if you delete the container. We also added a healthcheck that checks the database's readiness every ten seconds. The cache service is similar but simpler: a Redis image with a volume to store its data.

Finally, the volumes: section at the bottom of the file declares the two named volumes so that Docker manages them. Also notice depends_on in the web service: it doesn't just state that web depends on db, it requires condition: service_healthy. In other words, web doesn't start until the database health check actually succeeds, not merely when the container starts. This prevents a common error: the application starting before the database is ready and failing to connect.

The following diagram shows a similar real-world stack (running n8n on a VPS) with the same structure: a proxy, an application, a database and a persistent volume, all interconnected over a single Compose network:

Architecture for running n8n on a VPS with DockerInternet · HTTPS 443VPS server · Docker EngineReverse ProxyCaddy/Nginx + SSLn8n containerPort 5678PostgreSQLn8n data storagePersistent volumeEach service in an isolated container; the proxy terminates SSL and forwards to n8n on 5678
Running n8n on a VPS with Docker: a reverse proxy terminates SSL on 443 and forwards to the n8n container (5678), which is linked to a PostgreSQL database on a persistent volume.

How do services connect by service name?

This point confuses beginners more than any other, so it deserves its own explanation. When you run docker compose up, Compose automatically creates a private virtual network of the bridge type for your project and adds all the services to it. Inside this network, Docker runs an internal DNS server that maps each service name to the container's current address. So when the web application tries to connect to the host db, it looks up the name db and gets the database container's address directly.

The practical result: you don't write IP addresses anywhere, and you don't worry about them changing. Container addresses may change with every recreation, but the names stay the same. You write db:5432 in your application settings instead of 172.18.0.3:5432, and it keeps working however many times you restart. This automatic service discovery is what makes Compose files portable: copy the file to any server and it works, because nothing in it is tied to specific addresses.

A subtle point worth noting: the port another service uses inside the network is the container's internal port, not the port exposed in ports. In other words, web reaches the database at db:5432 (PostgreSQL's internal port) even if there is no ports key in the db service at all. The ports key exists only to expose a port to the outside world; internal communication between services always happens over the private network on the internal ports. This separation between "internal" and "exposed" is the foundation of a secure stack.

You can go further and split your services across more than one network for isolation. Picture a stack with a front-facing reverse proxy, a web application and a database: you put the proxy and the application on a "frontend" network, and the application and the database on a "backend" network, so the proxy can't see the database at all because they share no network. This split reduces the attack surface: if an attacker compromises the proxy, they don't even have a network path to your database. You don't need this complexity in every project, since a single default network is enough for most cases, but knowing the option exists gives you a powerful tool when your application grows and requires finer security separation between its layers.

Persistent data: named volumes vs. bind mounts

Containers are ephemeral by nature: delete the container and all the data in its internal file system is lost. That's acceptable for a stateless application such as a web server, but a disaster for a database. So you separate important data from the container's lifecycle using volumes. You have two main options, and the following table weighs them against each other:

CriterionNamed volumeBind mount
Storage locationManaged by Docker in its own areaA path you choose on the server
Best usePersistent database dataDevelopment code and configuration files
PortabilityHigh (no fixed path)Tied to the server's folder structure
PerformanceExcellent across platformsExcellent on Linux
BackupsThrough Docker toolsCopy the folder directly
Exampledb-data:/var/lib/..../config:/etc/app

The practical rule is simple: for persistent production data, above all databases, use named volumes, because they are isolated, managed by Docker, and portable without being tied to a specific path on the server. Bind mounts are ideal when you want the container to see a real folder on your server: an nginx.conf configuration file that you edit and reload, or application code you're developing live so that changes show up inside the container immediately. In the earlier example file we used a named volume, db-data, because it holds persistent database data, and that is the right choice.

Pay attention to deletion behavior here: docker compose down removes the containers and the network but keeps named volumes, so your data survives day-to-day stops and upgrades. But docker compose down -v removes the volumes too and the data is gone instantly. That's why you should never run the -v flag on a production server unless you fully intend to wipe everything and start from scratch. Fix this difference firmly in your mind before you type the command on a real server.

How do you manage environment variables and the .env file?

Applications need settings: database passwords, API keys, hostnames, run modes. Don't write these values directly in docker-compose.yml, especially secrets, because the file goes into Git. The solution is a .env file in the same folder containing KEY=VALUE pairs, which you reference from inside the Compose file with the ${VARIABLE} syntax. Notice in the example file that we wrote ${DB_PASSWORD} in two places; its actual value comes from a .env file like this:

bash
DB_PASSWORD=a-strong-random-password

When you run docker compose up, Compose reads the .env file automatically and substitutes each ${DB_PASSWORD} with its value. The benefit is twofold: you separate configuration from definition, and you keep secrets out of the committed file. The golden rule: add .env to .gitignore so it is never committed, and keep a .env.example file without real values so your team knows which variables are required without exposing their secrets. This separation between the application's "structure" (in the shared docker-compose.yml) and its "secrets" (in the local .env) is a fundamental practice.

When should you use Compose, and when do you need something else?

Docker Compose is a great tool, but it isn't the right tool for every situation. Understanding its limits saves you from complexity you don't need or from limitations that hold you back. The following table shows when to choose each approach:

ToolWhen it fitsExample
A single container (docker run)A simple, single-part, stateless applicationA static web server or a command-line tool
Docker ComposeA multi-container stack on a single serverWeb + database + cache on a VPS
Docker SwarmSimple distribution across several serversSeveral replicas of a service with load balancing
KubernetesLarge-scale orchestration with auto-scaling and self-healingA large platform with dozens of services and multiple teams

The practical rule: if your application is a single stateless container, a simple docker run container may be enough. But once it becomes several cooperating containers on a single server, which is the most common case for anyone hosting their applications on a VPS, Compose is the best choice by far. Things start to outgrow Compose when you need to distribute the application across multiple servers with automatic scaling, self-healing from failures, and zero-downtime rolling updates. That's where orchestration comes in: Kubernetes for large, complex projects, or Docker Swarm for a simpler need with a gentler learning curve.

But don't jump to Kubernetes before you actually need it; it is a huge amount of complexity that an application running happily on a single VPS with Compose doesn't justify. The vast majority of projects, including WordPress stores, small and medium SaaS platforms, and self-hosted automation tools (see installing n8n on a VPS), run excellently with Compose on a single well-resourced server. Move up to heavier orchestration only when a real need for horizontal scaling forces itself on you.

What are the key production tips for Docker Compose?

Writing a file that works on your machine is one thing; running it safely on a production server is another. Here is what separates an amateur setup from a production one, all of it applied in the earlier example file.

Restart policies: without a policy, your container won't come back if it crashes or the server reboots. Add restart: unless-stopped to every production service; it means "always restart unless I stop it manually." This ensures your application comes back automatically after any failure or system reboot, just as system services are managed through systemd. For that context, see managing Linux services.

Health checks: a container can appear to be running while the application inside it is broken. healthcheck defines a command that periodically checks actual health, such as pg_isready for a database or an HTTP request for a web application. When you pair the check with depends_on: condition: service_healthy, you ensure a service doesn't start until what it depends on is actually ready, not merely until its container has started.

Resource limits: a container without limits can eat all of the server's memory and bring down the rest. Set a memory and CPU cap for each service with the deploy.resources.limits key, so that a single service can't take down the whole stack during a memory leak or a sudden load spike.

Don't expose the ports of internal services: the most dangerous common mistake. Never add a ports key for the database or the cache. Services talk internally over the Compose network without any exposed port. Exposing port 5432 for a PostgreSQL database on a public IP means any bot on the internet can try to connect to it, and it is one of the most exploited server vulnerabilities.

Common errors and how to diagnose them

Even with a correct file, you'll run into problems at runtime. Here are the most common ones and how to fix them quickly.

"The service fails to connect to the database": usually one of two causes. First, the application started before the database was ready; the fix is depends_on with condition: service_healthy, as in the example. Second, you got the host address wrong; make sure you use the service name (db), not localhost or an IP. Inside the network, localhost means the container itself, not the database.

"Port is already allocated": another service on the server is holding the port you're trying to expose. Change the number on the left of ports (for example "8081:80" instead of "8080:80"), or stop the conflicting service. Use docker compose ps and system tools to find out what is holding the port.

"My data disappeared after a restart": you didn't attach a persistent volume to the service, or you ran down -v, which removes volumes. Make sure the service has a volumes key, that the volume is declared in the top-level volumes: section, and don't use -v with down in production.

"Changes to the file don't show up": after editing docker-compose.yml, you need to recreate the affected containers with docker compose up -d (Compose detects the difference and recreates only what changed). restart on its own restarts the container with its old settings without applying the change.

"YAML syntax error": indentation is very sensitive in YAML. Use spaces, not tabs, and keep two spaces per nesting level. Run docker compose config before anything else: it validates the file and prints the final resolved configuration, so you catch indentation errors immediately.

Conclusion

Docker Compose turns the exhausting chaos of managing several containers into a single clean text file that you can read, review and share. You define your services (each with its image, ports, volumes and variables) and then run the whole stack with one command, docker compose up -d. The beauty lies in the simplicity: an automatic network connects services by name so you don't need IP addresses, named volumes keep your data after containers are deleted, and a single file becomes the source of truth for your entire application architecture. This is the ideal model for anyone hosting their applications on a single VPS, from WordPress stores to self-hosted automation tools.

Remember the crucial points: use the modern docker compose command with a space and delete the obsolete version: key; always attach named volumes for any important data; never expose your database port to the world; and add restart policies and health checks before going to production. With these foundations, running complex applications on your server becomes a controlled, repeatable process instead of a fragile manual adventure. Compose doesn't just make things easier; it makes them reliable, and that is what you need when your business depends on the server staying up.

Frequently asked questions

What is the difference between Docker and Docker Compose? Docker runs a single container with the docker run command. Docker Compose is a layer on top of it that manages several containers together through a single docker-compose.yml file and the docker compose up command. Docker is the engine; Compose is the declarative orchestrator on top of it.

Does docker-compose (with a hyphen) still work? No. The old V1 tool written in Python has effectively been removed and is no longer supported. Use docker compose with a space (the V2 plugin built into Docker). The modern version is faster and compatible with old files with hardly any changes.

Do I need a version key at the top of the file? No. The version: key is now obsolete and is ignored entirely in the modern format, and Compose prints a warning if it finds one. Delete it and start your file directly with services:.

How do containers talk to each other in Compose? Through a private network that Compose creates automatically, on which each service reaches the others by name as if it were a hostname. So you write db:5432 or cache:6379 in your application settings, and Docker resolves the name to the correct container address without any intervention from you.

Where is the database data stored? In a named volume that you attach to the database's data path inside the container. The volume is independent of the container's lifecycle, so the data survives even if you delete the container and recreate it. Don't rely on the container's internal file system for any persistent data.

Does docker compose down delete my data? Not by default. down removes the containers and the network but keeps named volumes, so your data is safe. However, down -v removes the volumes too and the data is lost. Use it with great care and never run it in production unless you mean to.

How do I upgrade images to the latest version? Run docker compose pull to fetch the latest versions of the defined images, then docker compose up -d to recreate only the containers affected by the new images. Compose leaves unchanged services running without interruption.

How do I see the errors of a failing service? Use docker compose logs -f service-name to follow its logs in real time, or docker compose ps to see the status of all services. If the file itself is in doubt, docker compose config validates it and prints the resolved configuration.

Is Compose suitable for production or only for development? It is perfectly suitable for production on a single server, and it is the most common choice for VPS applications. Add restart policies, health checks and resource limits, and don't expose the ports of internal services. You need something heavier (Swarm or Kubernetes) only when distributing across multiple servers with automatic scaling.

When should I move from Compose to Kubernetes? When you need to distribute your application across multiple servers with automatic scaling, self-healing and zero-downtime rolling updates. As long as your application runs happily on a single VPS, Compose is simpler and more efficient, and the huge complexity of Kubernetes isn't justified until the need to scale genuinely forces itself on you.

Sources

Frequently asked questions

What is the difference between Docker and Docker Compose?

Docker runs a single container with the docker run command. Docker Compose is a layer on top of it that manages several containers together through a single docker-compose.yml file and the docker compose up command. Docker is the engine; Compose is the declarative orchestrator on top of it.

Does docker-compose (with a hyphen) still work?

No. The old V1 tool written in Python has effectively been removed and is no longer supported. Use docker compose with a space (the V2 plugin built into Docker). The modern version is faster and compatible with old files with hardly any changes.

Do I need a version key at the top of the file?

No. The version: key is now obsolete and is ignored entirely in the modern format, and Compose prints a warning if it finds one. Delete it and start your file directly with services:.

How do containers talk to each other in Compose?

Through a private network that Compose creates automatically, on which each service reaches the others by name as if it were a hostname. So you write db:5432 or cache:6379 in your application settings, and Docker resolves the name to the correct container address without any intervention from you.

Where is the database data stored?

In a named volume that you attach to the database's data path inside the container. The volume is independent of the container's lifecycle, so the data survives even if you delete the container and recreate it. Don't rely on the container's internal file system for any persistent data.

Does docker compose down delete my data?

Not by default. down removes the containers and the network but keeps named volumes, so your data is safe. However, down -v removes the volumes too and the data is lost. Use it with great care and never run it in production unless you mean to.

How do I upgrade images to the latest version?

Run docker compose pull to fetch the latest versions of the defined images, then docker compose up -d to recreate only the containers affected by the new images. Compose leaves unchanged services running without interruption.

How do I see the errors of a failing service?

Use docker compose logs -f service-name to follow its logs in real time, or docker compose ps to see the status of all services. If the file itself is in doubt, docker compose config validates it and prints the resolved configuration.

Is Compose suitable for production or only for development?

It is perfectly suitable for production on a single server, and it is the most common choice for VPS applications. Add restart policies, health checks and resource limits, and don't expose the ports of internal services. You need something heavier (Swarm or Kubernetes) only when distributing across multiple servers with automatic scaling.

When should I move from Compose to Kubernetes?

When you need to distribute your application across multiple servers with automatic scaling, self-healing and zero-downtime rolling updates. As long as your application runs happily on a single VPS, Compose is simpler and more efficient, and the huge complexity of Kubernetes isn't justified until the need to scale genuinely forces itself on you.