0
0
Dockerdevops~30 mins

Environment variables in Compose in Docker - Mini Project: Build & Apply

Choose your learning style9 modes available
Environment variables in Compose
📖 Scenario: You are setting up a simple web application using Docker Compose. You want to use environment variables to configure the application port and a greeting message.
🎯 Goal: Build a Docker Compose file that uses environment variables to set the port and greeting message for a web service.
📋 What You'll Learn
Create a Docker Compose file with a service named webapp
Use environment variables APP_PORT and GREETING in the Compose file
Set default values for these environment variables in the Compose file
Print the environment variables inside the container using a simple command
💡 Why This Matters
🌍 Real World
Environment variables in Docker Compose help configure containers without changing code or images. This is common in real projects to manage settings like ports, credentials, or messages.
💼 Career
Understanding environment variables in Compose is essential for DevOps roles to build flexible, configurable containerized applications.
Progress0 / 4 steps
1
Create the basic Docker Compose file
Create a file named docker-compose.yml with a service called webapp that uses the image alpine and runs the command sh -c "echo Hello".
Docker
Need a hint?

Use the services key, then define webapp with image and command.

2
Add environment variables with default values
Add environment variables APP_PORT with default 8080 and GREETING with default Hello, World! under the webapp service using the environment key.
Docker
Need a hint?

Use the environment key as a map with keys APP_PORT and GREETING.

3
Modify the command to print environment variables
Change the command of the webapp service to print both environment variables APP_PORT and GREETING using sh -c and echo. The command should print: Port: $APP_PORT, Message: $GREETING.
Docker
Need a hint?

Use sh -c "echo Port: $APP_PORT, Message: $GREETING" as the command.

4
Run the Compose service and show output
Run docker-compose run webapp and print the output that shows the port and greeting message from the environment variables.
Docker
Need a hint?

Use the terminal command docker-compose run webapp to see the output.