0
0
DockerHow-ToBeginner · 4 min read

How to Define a Service in Docker Compose: Syntax and Example

In Docker Compose, a service is defined under the services key in the docker-compose.yml file. Each service specifies a container configuration like the image, ports, and environment variables to run your app.
📐

Syntax

A service is defined inside the services section of the docker-compose.yml file. Each service has a name and configuration options such as image, build, ports, and environment.

Example parts:

  • service_name: The name of your service.
  • image: The Docker image to use.
  • build: Path to Dockerfile if building locally.
  • ports: Port mappings from host to container.
  • environment: Environment variables inside the container.
yaml
version: '3.8'
services:
  service_name:
    image: image_name:tag
    build: ./path_to_dockerfile
    ports:
      - "host_port:container_port"
    environment:
      - ENV_VAR=value
💻

Example

This example defines a simple web service using the official Nginx image. It maps port 8080 on your computer to port 80 inside the container.

yaml
version: '3.8'
services:
  web:
    image: nginx:1.23
    ports:
      - "8080:80"
Output
Creating network "default" with the default driver Creating service "web" ... done # When you run 'docker-compose up' this starts the nginx container accessible at localhost:8080
⚠️

Common Pitfalls

Common mistakes when defining services include:

  • Indentation errors in docker-compose.yml which cause parsing failures.
  • Using image and build together incorrectly; choose one per service.
  • Forgetting to map ports, so the service is not accessible from your host.
  • Not specifying environment variables needed by the container.
yaml
version: '3.8'
services:
  app:
    image: myapp:latest
    # build: ./app
    ports:
      - "5000:5000"

# Correct approach is to use either 'image' or 'build', not both unless you know what you are doing.
📊

Quick Reference

KeyDescriptionExample
servicesTop-level key to define all servicesservices:
service_nameName of the serviceweb:
imageDocker image to useimage: nginx:1.23
buildBuild context or Dockerfile pathbuild: ./app
portsHost to container port mappingports: - "8080:80"
environmentEnvironment variables inside containerenvironment: - DEBUG=true

Key Takeaways

Define each service under the 'services' key in docker-compose.yml.
Use either 'image' to pull or 'build' to create a container image for a service.
Map ports to access services from your host machine.
Indentation and YAML syntax must be correct to avoid errors.
Set environment variables inside services to configure containers.