Configuring Docker Compose Ports via Environment Variables

Docker Compose is a powerful tool that allows developers to define multi-container applications and easily manage them. One of the key features of Docker Compose is its ability to map container ports to host machine ports, enabling seamless communication between the two.

In this article, we'll explore how to use environment variables to dynamically set the port in the docker-compose.yml file. By leveraging environment variables, we can make our Docker Compose configuration more flexible, portable, and suitable for various deployment scenarios.

Understanding the Docker Compose Configuration

Before we dive into using environment variables, let's briefly review the typical structure of a docker-compose.yml file. In this example, we have a simple service defined, and we want to map its internal container port to a port on the host machine.

version: '3.8'

services:
  web_app:
    image: my_web_app_image
    ports:
      - "${OUT_PORT}:80"

Here, we have a service named web_app, which uses the my_web_app_image Docker image. The ports section is where we define the port mapping. The notation ${OUT_PORT} indicates that we will use the value of the OUT_PORT environment variable for the host machine port.

Setting Environment Variables in GitLab CI

To make use of environment variables, we need to define and set them in our CI/CD pipeline. In this example, we are using GitLab CI, and we'll add the necessary configuration in the .gitlab-ci.yml file.

variables:
  OUT_PORT: 18080

Here, we set the OUT_PORT environment variable to 18080. This value will be used by Docker Compose to determine the port on the host machine that the web_app service should be accessible through.

Advantages of Using Environment Variables
  1. Flexibility: Environment variables allow us to decouple the port configuration from the docker-compose.yml file. This means we can easily adjust the port without modifying the entire configuration.

  2. Portability: By using environment variables, we create a configuration that can be shared across different environments and projects. It provides consistency and avoids hardcoded values that may not be suitable for all setups.

  3. Security: When dealing with sensitive information like ports or credentials, environment variables offer a more secure approach. We can manage these variables separately and prevent accidental exposure of sensitive data.

Using environment variables to set the port in a Docker Compose configuration enhances the flexibility, portability, and security of our applications. By embracing this approach, we can seamlessly adapt our services to various environments and avoid common pitfalls associated with hardcoded configurations.

2023-06-19 10:11:23 | NOTE | 0 Comments
 

 

Leave A Comment

RELATED STORIES


MOST RECENTLY