CodeBlanks Logo Icon CodeBlanks

Service definition

Add a web service to the compose file.

Service definition

A service can be created from a ready image (image:) or from a Dockerfile in the project (build:). Each docker run option has a Compose counterpart:

services:
  api:
    build: .
    image: api:dev
    ports:
      - "8000:8000"
    environment:
      LOG_LEVEL: info
    restart: unless-stopped

When build and image are written together, the built image is tagged with that name.

Build details

In long form, build can take the context, Dockerfile and build arguments. When the code changes, the image is rebuilt with --build:

services:
  api:
    build:
      context: ./api
      dockerfile: Dockerfile
      args:
        SURUM: "1.0.0"

docker compose up -d --build

Compose uses the project folder's name (or -p) as a prefix: the container name becomes proje-api-1.

Practice The API service

Write the api service in compose.yaml: built from the current folder (build: .); publishing port 8000 with the same number; LOG_LEVEL: info under environment; restart: unless-stopped.

Starter code

terminal
# compose.yaml
services:
# buraya yaz

Sample solution

terminal
# compose.yaml
services:
  api:
    build: .
    ports:
      - "8000:8000"
    environment:
      LOG_LEVEL: info
    restart: unless-stopped

Expected output

[+] Running 2/2
 ✔ Image proje-api  Built
 ✔ Container proje-api-1  Started

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the Compose counterpart of the docker run -e LOG_LEVEL=info option?

  • args: LOG_LEVEL=info
  • LOG_LEVEL: info under environment Correct answer
  • env: LOG_LEVEL
  • vars: [info]

Explanation: environment can be written both as a map and as a list (- NAME=value).

2 Create the service from the Dockerfile in the project.

Question
services:
  api:
    ____: .
Answer
services:
  api:
    build: .

Explanation: build points at the context folder.

3 Match the docker run counterparts.

Term Meaning
-p 8000:8000 ports
-e NAME=value environment
--restart restart
docker build . build: .

All lessons in Beginner