Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk10 min

How to Run Multiple Containers with Docker Compose

Build and operate a multi-container application with Docker Compose. This guide covers compose.yaml, service-name networking, database readiness checks, persistent volumes, profiles, environment overrides, lifecycle commands, and common fixes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Docker Compose to describe your application’s containers in one compose.yaml file, then start the whole stack with docker compose up. Each container is declared as a named service. Compose creates the project network, starts the services in dependency order, and manages their lifecycle together.

The practical details that determine whether a multi-container setup works are readiness checks, service-name networking, persistent volumes, and environment-specific service selection. The walkthrough below builds a web service and PostgreSQL database, then shows how to operate, adapt, and troubleshoot the stack.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What Docker Compose does

Docker describes Compose as “a tool for defining and running multi-container applications.” Instead of starting every container with separate docker run commands, you keep the application model in YAML. The model records each service’s image or build context, ports, environment variables, dependencies, health checks, networks, and storage.

Run Compose commands from the directory containing the file. Compose treats that directory and its project name as the scope for the resources it creates, so the services, network, and named volumes belonging to one application can be operated together.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

When Compose is a good fit

  • Local development where an application needs several cooperating containers.
  • Repeatable test or demonstration environments.
  • Small deployments where one Compose model should define the complete application stack.
  • Optional supporting tools, such as a debugger or administration interface, that should remain available without starting on every run.

What Compose does not guarantee by itself

Starting a dependency first does not prove that the dependency is ready to accept requests. A database process can be running while it is still initializing. If an application must wait for readiness, pair a database healthcheck with the long-form depends_on condition described later.

Prerequisites and project layout

Install Docker with the Compose command available as docker compose. Create a project directory containing your application source and a file named compose.yaml. The example below assumes the web service has a Dockerfile in the project directory, because its service uses build: ..

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A simple layout can look like this:

my-app/
├── compose.yaml
├── Dockerfile
└── application-source/

The database image is pulled automatically if it is not already present. The web image is built from the local Dockerfile when Compose starts the stack.

A minimal two-container Compose application

Save this as compose.yaml:

services:
  web:
    build: .
    ports:
      - "8080:8080"
    environment:
      DATABASE_URL: postgres://app:secret@db:5432/app
    depends_on:
      db:
        condition: service_healthy

  db:
    image: postgres:18
    environment:
      POSTGRES_DB: app
      POSTGRES_USER: app
      POSTGRES_PASSWORD: secret
    volumes:
      - db-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
      interval: 5s
      timeout: 5s
      retries: 10

volumes:
  db-data:

The web service

build: . tells Compose to build an image using the Dockerfile in the current directory. The ports entry publishes host port 8080 to port 8080 in the web container, allowing a browser or another host process to reach the application at that published port.

The DATABASE_URL value deliberately uses db as the hostname. db is the service key, and Compose provides DNS resolution for that name on the project network. The URL therefore targets PostgreSQL’s container port 5432 rather than a host-published port.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

The long-form dependency declaration says that web may start after db reports healthy. That condition only has meaning because the database service defines a health check.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The db service

image: postgres:18 selects the PostgreSQL image and tag used by this example. The three environment variables initialize the database name, user, and password expected by the application.

The healthcheck runs pg_isready through CMD-SHELL. Compose checks it every five seconds, allows five seconds for each attempt, and retries ten times. These values are part of the readiness policy: adjust them when initialization routinely takes longer or when checks are too aggressive.

The named volume

The top-level volumes declaration creates the named volume db-data. The service mounts it at PostgreSQL’s data directory, so the database files live outside the container’s disposable writable layer. Recreating the database container does not erase that volume unless you explicitly remove it.

Start and inspect the stack

  1. Open a terminal in the directory containing compose.yaml.
  2. Start the application in the background with docker compose up -d. Compose builds the web image if necessary, pulls the database image if needed, creates the project network and named volume, and starts the services.
  3. Check service state with docker compose ps. Confirm that both services are running and that the database health status becomes healthy.
  4. Follow the web service logs with docker compose logs -f web. Press Ctrl+C to stop following logs; this does not stop the services.

For a foreground run, omit -d. The terminal then displays service output until you interrupt it. Foreground mode is useful when diagnosing an initial startup failure.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Commands you will use repeatedly

Command Purpose
docker compose up -d Build or pull required images and start the declared services in detached mode.
docker compose up --build Rebuild images before starting, useful after changing the Dockerfile or application image contents.
docker compose ps Show the project’s service and container state.
docker compose logs -f web Follow logs for one service; replace web with another service name as needed.
docker compose run --rm web <command> Run a one-off command with the web service configuration, then remove that temporary container.
docker compose down Stop and remove the project’s containers and network while retaining declared named-volume data.
docker compose down -v Stop and remove containers, networks, and named volumes. Use only when deleting the stored data is intentional.
docker compose config Render and validate the Compose model after files, profiles, or overrides are merged.

How containers find one another

Compose normally creates one default project network and attaches every service to it. Containers on that network can address one another by service name. In the example, the web container connects to db:5432; it should not use a container IP address, because container IPs can change when services are recreated.

Use the container port for internal traffic. The 8080:8080 mapping is needed for access from the host, but a second service connecting to the web service would use the web service name and its container port. Publishing every internal port unnecessarily increases exposure and is not required for service-to-service communication.

Separate networks when isolation matters

You can declare custom top-level networks and attach services selectively. For example, a front-end service and web service can share a network while the database is attached only to the web network:

services:
  frontend:
    image: example-frontend
    networks:
      - edge

  web:
    build: .
    networks:
      - edge
      - data

  db:
    image: postgres:18
    networks:
      - data

networks:
  edge:
  data:

In this arrangement, frontend can reach web through edge, while only web can reach db through data. Compose also supports external networks when a service must join a network managed outside this project.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Startup order versus application readiness

The short dependency form establishes startup order but does not wait for a dependency to become healthy. This distinction explains many “connection refused” errors during first boot.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Order-only dependency

services:
  web:
    build: .
    depends_on:
      - db
  db:
    image: postgres:18

Compose starts db before web, but web can still begin while PostgreSQL is initializing.

Health-gated dependency

services:
  web:
    build: .
    depends_on:
      db:
        condition: service_healthy

  db:
    image: postgres:18
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
      interval: 5s
      timeout: 5s
      retries: 10

The long form tells Compose to wait until the database health check succeeds before starting the web service. A health check can be a string or a list beginning with CMD, CMD-SHELL, or NONE. Its interval, timeout, retries, and optional start_period determine how Compose evaluates the result.

Choose a check that tests the capability the dependent service actually needs. A process-level check that merely confirms a program exists is weaker than a database readiness command such as pg_isready.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep data when containers are recreated

A container’s writable layer is disposable. Removing and recreating a container removes files stored only there. Stateful services therefore need a volume mounted at the directory where they store data.

In the example, db-data is mounted at /var/lib/postgresql/data. Running docker compose down removes the containers and their writable layers but leaves the named volume. Starting the project again reuses the existing database files.

Prevent accidental deletion

  • Use docker compose down for ordinary shutdown and cleanup.
  • Treat docker compose down -v as a destructive data operation; it removes the named volumes declared by the project.
  • Verify the volume mount in compose.yaml before troubleshooting an apparent data loss.
  • When sharing a named volume between services, ensure the services agree on its file layout and access requirements.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Run optional services with profiles

Profiles keep optional components in the same Compose model without starting them on every run. A service assigned to a profile remains inactive until that profile is enabled.

services:
  web:
    build: .

  debug:
    image: example-debugger
    profiles:
      - debug

Start the normal stack without the debugger using docker compose up -d. Enable it explicitly with docker compose --profile debug up -d. You can also set COMPOSE_PROFILES=debug in the environment. Multiple --profile flags can be supplied when several optional groups are needed.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Profiles are appropriate when the difference is whether a service runs. If the same services need different images, environment variables, mounts, or ports for development and production, use environment-specific Compose files instead.

Layer development and production configuration

Keep common service definitions in a base Compose file and layer environment-specific files with -f. The merged model is what Compose uses, so validate it before starting:

docker compose -f compose.yaml -f compose.production.yaml config
docker compose -f compose.yaml -f compose.production.yaml up -d

The first command lets you inspect the effective configuration and catch an unexpected merge before containers are changed. Profiles can coexist with file layering: use profiles for optional services and override files for substantive configuration differences.

Rebuild, recreate, and update safely

When application code is baked into the web image, changing the source does not necessarily change an already-created container. Use docker compose up --build to rebuild the image and apply it. Inspect logs afterward with docker compose logs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If the Compose model changes, rerun docker compose config and then start the stack again. Compose recreates services whose configuration or image has changed while leaving unaffected resources in place. The named database volume remains separate from that container replacement.

Troubleshooting common failures

Symptom Likely cause Fix
The application cannot resolve db. The services are not on a shared Compose network, or the application is using a different hostname. Attach both services to the same network and use the exact service key, db, as the hostname.
The application starts before PostgreSQL accepts connections. depends_on is being used only for order, without a readiness check. Add the database healthcheck and use condition: service_healthy.
Database data appears to be gone. The database directory was not backed by a named volume, or down -v removed it. Mount a named volume at the database data directory and avoid down -v unless deletion is intended.
Port 8080 is already occupied. Another host process or container owns the published host port. Stop the conflicting process or change the host side of the mapping, for example 8081:8080. Internal traffic can continue using the container port.
Configuration changes have no visible effect. The merged model or image was not updated, or an old container is still running. Run docker compose config, then use docker compose up --build when the image must be rebuilt and inspect service logs.
Only a subset of services is needed. All always-on services are being started together. Use profiles for optional components or specify the target service names on the Compose command line.

Choose the right Compose design

Design decision Use this when Trade-off
Short depends_on Only startup order matters, or the application has its own retry logic. Does not wait for dependency readiness.
Health-gated dependency The dependent service must not start until a concrete readiness test succeeds. Requires a meaningful health check and suitable timing values.
Container writable layer Data is disposable, such as a cache or temporary output. Data disappears when the container is removed.
Named volume Database or other state must survive container recreation. Requires deliberate lifecycle management; down -v deletes it.
Published port The host or an outside network must access a service. Consumes a host port and exposes that service beyond the internal network.
Internal service networking One Compose service needs another. Clients must use the service name and container port.
Profiles An optional service should remain defined but inactive by default. Operators must enable the relevant profile.
Override files Development and production need different service settings. The effective configuration can be harder to see unless you inspect it with docker compose config.

A repeatable operating checklist

  1. Confirm the file is named compose.yaml and is in the directory where you will run Compose commands.
  2. Check that every application dependency has a service key and that connection strings use those keys rather than container IP addresses.
  3. Publish only ports that the host or an outside network must reach.
  4. Add a health check for services whose readiness matters, then use service_healthy for dependent services.
  5. Mount named volumes for databases and other state that must survive recreation.
  6. Run docker compose config after changing files, profiles, or overrides.
  7. Start with docker compose up -d or docker compose up --build when an image rebuild is required.
  8. Use docker compose ps and targeted docker compose logs -f SERVICE commands to verify behavior.
  9. Stop with docker compose down; reserve down -v for intentional volume deletion.

Bottom line

A reliable multi-container Compose application has one clear YAML model, service-name DNS for internal connections, health-gated dependencies where readiness matters, and named volumes for state. Start it with docker compose up, validate merged configuration before changes, and use profiles or override files to control which services and settings apply in each environment.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.