0
0
Dockerdevops~30 mins

Init container pattern in Docker - Mini Project: Build & Apply

Choose your learning style9 modes available
Init Container Pattern in Docker
📖 Scenario: You are setting up a Docker environment where an application container depends on some initialization tasks to be completed first. This is common in real-world deployments where setup steps must finish before the main app runs.
🎯 Goal: Build a Docker Compose setup with an init container that runs a setup script before the main application container starts.
📋 What You'll Learn
Create a Docker Compose file with two services: init and app
The init service runs a simple shell command to create a file
The app service waits for the init service to complete before starting
Use the depends_on option to enforce startup order
💡 Why This Matters
🌍 Real World
Init containers are used in real deployments to prepare the environment, such as setting up config files or databases, before the main application starts.
💼 Career
Understanding init containers and service dependencies is important for DevOps roles managing containerized applications and orchestrations.
Progress0 / 4 steps
1
Create Docker Compose file with init and app services
Create a file named docker-compose.yml with two services: init and app. The init service should use the alpine image and run the command sh -c "echo Init done > /shared/init.txt". Add a top-level volumes section defining a named volume shared, and mount it to /shared in both services using volumes: - shared:/shared. The app service should use the alpine image and run sh -c "sleep 10" as a placeholder command.
Docker
Need a hint?

Use version: '3.8' at the top. Define two services named exactly init and app. Use the alpine image for both. Add top-level volumes: shared: and volumes: - shared:/shared under both services.

2
Add depends_on to app service
Modify the app service in docker-compose.yml to include depends_on using the map format so that the app service waits for the init service to complete successfully before starting. Use condition: service_completed_successfully.
Docker
Need a hint?

Under the app service, add depends_on: as a map containing init: with condition: service_completed_successfully.

3
Change app command to check init file
Change the app service's command to sh -c "while [ ! -f /shared/init.txt ]; do sleep 1; done; echo Init file found; sleep 5" so it waits until the /shared/init.txt file created by the init service exists.
Docker
Need a hint?

Use a shell loop in the app command to wait for the file /shared/init.txt.

4
Run docker-compose and show app output
Run docker-compose up in your terminal to start both services. Then write the exact output line from the app service that says Init file found.
Docker
Need a hint?

Look for the line printed by the app service after it detects the init file.