I want to run multiple container using docker compose, the image and settings are always…
- User
I want to run multiple container using docker compose, the image and settings are always the same, only thing is one environment variable is changing and the port. What would be a nice way to write the docker compose file ?
- Assistant
To share the same Docker Compose setup across multiple environments, you can use the
environment_variablesoption. This allows you to define a set of environment variables that are shared across all containers in the same service.Here's an example Docker Compose file that defines an environment variable called
PORTand sets it to5000in the development environment, and to5001in the production environment:yamlversion: '3' services: web: build:. ports: - "5000:5000" environment: - PORT=5000 redis: image: "redis:alpine" environment: - PORT=5001In this example, the
webservice has two containers: one that builds the application from the current directory and exposes port 5000, and another that uses the redis image and exposes port 5001. The section of each service defines the environment variables that are used by the containers. - User
There are a bunch of env variable for each container, can i make it less redudantant ?
- Assistant
Yes, you can use the environment variables for each container in a more concise way by using the
environment_variablesoption in the Docker Compose file.Here's an example Docker Compose file that defines the
PORTenvironment variable in a simplified way:yamlversion: '3' services: web: build:. ports: - 5000 environment: - PORT=5000 redis: image: "redis:alpine" environment: - PORT=5001In this example, the
webservice has only one container that uses the default build configuration and exposes port 5000. Theredisservice uses the same redis image and exposes port 5001.By using the
environment_variablesoption, you can define thePORTenvironment variable once and reuse it throughout your project, making your Docker Compose file more concise and easier to maintain. - User
a
- Assistant
Thank you for your feedback! I'm glad I could be of assistance. If you have any other questions, feel free to ask.