How to Orchestrate Three Containers with Docker-Compose

Abstract: Solve multi-container orchestration by defining services in docker-compose.yml with shared networks and dependency management for seamless communication.

Created: 2026-09-09 by
You can orchestrate three containers with Docker Compose by defining each service in a single docker-compose.yml file, assigning them unique names, and connecting them to a shared custom network. This approach allows services to resolve each other by hostname automatically, enabling seamless communication without exposing unnecessary ports to the host machine.

Defining the Services

The foundation of any Docker Compose setup is the docker-compose.yml file. To orchestrate three distinct containers, you must define each one under the services key. Each service represents a running container and requires at least an image or build context. For this example, we will create a simple architecture consisting of a web frontend, an API backend, and a database. Start by creating a directory for your project and adding the docker-compose.yml file inside it. The structure should look like this:
version: '3.8'

services:
  frontend:
    image: nginx:latest
    ports:
      - "8080:80"
    depends_on:
      - api

  api:
    image: node:14-alpine
    command: npm start
    environment:
      - DB_HOST=database
      - DB_PORT=5432
    depends_on:
      - database

  database:
    image: postgres:13
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
      POSTGRES_DB: mydb
    volumes:
      - db_data:/var/lib/postgresql/data

volumes:
  db_data:
In this configuration, the frontend service uses Nginx to serve static files. It exposes port 8080 on the host to port 80 in the container. The depends_on directive ensures that the API starts before the frontend, although it does not wait for the API to be ready. The api service runs a Node.js application and connects to the database using environment variables. Crucially, the DB_HOST is set to database, which matches the service name defined below. The database service uses PostgreSQL and persists data using a named volume called db_data.

Networking and Communication

One of the most powerful features of Docker Compose is its default networking model. By default, all services defined in the same docker-compose.yml file are placed on the same network. This allows containers to communicate with each other using their service names as hostnames. You do not need to manually configure IP addresses or use complex routing rules. When the api container attempts to connect to postgresql://user:password@database:5432/mydb, Docker resolves database to the internal IP address of the database container. This DNS resolution happens automatically within the Compose network. If you require more control, you can define a custom network explicitly:
networks:
  app_network:
    driver: bridge

services:
  frontend:
    networks:
      - app_network
  api:
    networks:
      - app_network
  database:
    networks:
      - app_network
Using a custom network provides better isolation if you plan to add other services later that should not have access to the database. It also makes the intent of your architecture clearer. For most small applications, however, the default bridge network created by Compose is sufficient and easier to manage.

Managing Dependencies

The order in which containers start matters, especially when services rely on each other being available. Docker Compose handles basic startup ordering through the depends_on instruction. In our example, the frontend depends on the API, and the API depends on the database. This ensures that the database starts first, followed by the API, and finally the frontend. However, depends_on only waits for the container to start, not for the application inside to be ready. A database might take several seconds to initialize after the container process begins. If your API tries to connect immediately upon starting, it might fail. To handle this, you can implement retry logic in your application code or use a tool like wait-for-it as an entrypoint script. Alternatively, you can use health checks to ensure dependencies are truly ready before dependent services start. Adding health checks improves reliability significantly. You can define a health check for the database service:
healthcheck:
  test: ["CMD-SHELL", "pg_isready -U user -d mydb"]
  interval: 10s
  timeout: 5s
  retries: 5
Then, update the depends_on clause to include the health condition:
depends_on:
  database:
    condition: service_healthy
This ensures that the API will not start until the database is actively accepting connections. This pattern is essential for production-like environments where timing issues can cause cascading failures.

Running and Debugging

Once your docker-compose.yml file is configured, you can start the entire stack with a single command. Navigate to the directory containing the file and run: docker compose up -d The -d flag runs the containers in detached mode, allowing you to continue using your terminal. You can monitor the logs of all services combined by running: docker compose logs -f If a service fails to start, you can view the logs for a specific container using: docker compose logs api To stop the services without removing them, use: docker compose stop To completely remove the containers and networks, run: docker compose down If you need to rebuild images after changing code, add the --build flag to the up command. This is particularly useful during development when you frequently update source code. For troubleshooting connectivity issues, you can enter a running container using: docker compose exec api sh Inside the container, you can use tools like ping or curl to test connectivity to other services. For example, running curl http://database:5432 from the API container helps verify that the database is reachable. If you encounter persistent connection refused errors, check the health status of the database container and ensure the correct port is exposed internally.

Frequently Asked Questions

How do I expose a database port to the host?

Add a ports section to the database service definition in your docker-compose.yml file. Map the host port to the container port, such as "5432:5432" for PostgreSQL. Be cautious with this in production, as it exposes the database directly to the network.

Can I use different versions of Docker Compose?

Yes, but version 3.8 is widely supported and recommended for most use cases. Newer versions may introduce features like deploy configurations for swarm mode, which are not needed for local development. Stick to version 3.x unless you have specific requirements for newer syntax.

What happens if a container crashes repeatedly?

Docker Compose will attempt to restart the container according to the default restart policy. You can customize this by adding a restart policy, such as always or on-failure, to the service definition. Check the logs to determine the root cause of the crash.

How do I share files between containers?

Use volumes to mount directories from your host machine into the containers. This allows multiple containers to read and write to the same files. For example, you can mount a shared code directory for both the frontend and API services to facilitate synchronized development.

Is it safe to commit changes to Docker Compose files?

Yes, docker-compose.yml files are meant to be version-controlled. They define the infrastructure as code. However, avoid committing sensitive information like passwords or API keys. Use environment variables or Docker secrets instead to keep credentials secure.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More