CodeBlanks Logo Icon CodeBlanks

Challenge - Beginner project

Set up a project that combines all beginner concepts.

Challenge: the beginner project

All the pieces of the beginner section: an API built with your own Dockerfile, a Redis cache, a shared network, environment variables and a health check. The Compose file defines both the build and the run:

services:
  api:
    build: .
    image: api:1.0.0
    ports:
      - "3000:3000"
    env_file: api.env
    environment:
      REDIS_URL: redis://cache:6379
    depends_on:
      cache:
        condition: service_healthy
    restart: unless-stopped
  cache:
    image: redis:7
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s

Practice The project's compose file

Write a compose.yaml: the api service with build: ., image: api:1.0.0, "3000:3000", env_file: api.env, and condition: service_healthy for cache under depends_on; the cache service with redis:7 and test: ["CMD", "redis-cli", "ping"] under healthcheck.

Starter code

terminal
# compose.yaml
# buraya yaz

Sample solution

terminal
# compose.yaml
services:
  api:
    build: .
    image: api:1.0.0
    ports:
      - "3000:3000"
    env_file: api.env
    depends_on:
      cache:
        condition: service_healthy
  cache:
    image: redis:7
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]

Expected output

[+] Running 3/3
 ✔ Image api:1.0.0  Built
 ✔ Container proje-cache-1  Healthy
 ✔ Container proje-api-1  Started

Practice Update the code

You changed the code. Write two commands: rebuild only the api service and update it in the background; then show the variables by running the env command in the api container.

Starter code

terminal
# buraya yaz

Sample solution

terminal
docker compose up -d --build api
docker compose exec api env

Expected output

[+] Running 2/2
 ✔ Image api:1.0.0  Built
 ✔ Container proje-api-1  Started
NODE_ENV=production
REDIS_URL=redis://cache:6379
LOG_LEVEL=info

Questions and answers

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

1 When does the cache service's healthcheck succeed?

  • Always after 5 seconds
  • When api starts
  • When redis-cli ping returns with a zero exit code (PONG) Correct answer
  • As soon as the container starts

Explanation: The health check looks at the test command's exit code.

2 Load the environment variables from a file.

Question
  api:
    build: .
    ____: api.env
Answer
  api:
    build: .
    env_file: api.env

Explanation: In Compose it is written with an underscore: env_file.

3 Match.

Term Meaning
build: . Your own Dockerfile
image: api:1.0.0 Build tag
env_file Settings from file
service_healthy Start when ready

All lessons in Beginner