Back to roadmaps docker-compose Course

Defining Services: Build, Images, and Port Mappings

The services node is the core of a docker-compose.yml file. Each child node represents a container service in your application.


1. Using Pre-built Registry Images

To run a service using a pre-built image from Docker Hub, use the image directive:

services:
  cache-server:
    image: redis:7-alpine
    container_name: cache-redis

2. Building Images from Local Dockerfiles

If you are developing a custom application, you can instruct Compose to build the image from a local Dockerfile using the build directive:

services:
  api-server:
    build:
      context: ./backend # Path containing the Dockerfile
      dockerfile: Dockerfile # Name of the target Dockerfile

3. Configuring Port Mappings

To expose container ports to your host machine, use the ports directive. The format is host_port:container_port:

services:
  web:
    image: nginx:alpine
    ports:
      - "8080:80" # Map host port 8080 to container web port 80
      - "8443:443" # Map host port 8443 to container SSL port 443

Note: Always wrap port mappings in quotes (for example, "80:80") to prevent YAML parsers from misinterpreting numbers as sexagesimal (base 60) values.

Published on Last updated: