Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign port dynamically using docker-compose?

I am doing dockerization of project. I wanted to assign port in the docker-compose file dynamically.

I have searched over the internet but I am not able to find any solution. Any suggestions are welcome

services:
  db:
    image: "mysql:latest"
    restart: on-failure
    environment:
      - MYSQL_ROOT_PASSWORD=
      - MYSQL_DATABASE=
    ports:
      - 23316:3305

Docker-compose port should not be assign to particular port. It should be dynamically generated.

like image 450
Sachin Bankar Avatar asked Jun 27 '26 15:06

Sachin Bankar


2 Answers

You can create separate .env files to keep your environment dependent variables, and refer to those vars in your compose file as below:

version: '3'

services:
  db:
    image: "mysql:latest"
    restart: on-failure
    environment:
      - MYSQL_ROOT_PASSWORD=
      - MYSQL_DATABASE=
    ports:
      - ${DB_PORT}:3306

development .env file

DB_PORT=3306

production .env file

DB_PORT=23316

Copy either the .env file above to your server, and place it in the same dir with your docker-compose.yml file.

When you run the docker-compose command, it will automatically replace the env vars in the compose file with what you have defined in .env file.

Suppose you have deployed the production .env file with your docker-compose.yml, then when you run command

docker-compose up -d

DB_PORT will be replace with 23316.

Reference:

  1. Environment variables in Compose
  2. Environment file
like image 161
Enix Avatar answered Jun 30 '26 07:06

Enix


You can use environment variables:

version: '3'

services:
  db:
    image: mysql
    restart: on-failure
    environment:
      - MYSQL_ROOT_PASSWORD=
      - MYSQL_DATABASE=
    ports:
      - ${MYSQL_PORT}:3306

and then just define them at runtime like this:

MYSQL_PORT=3306 docker-compose up
like image 42
constt Avatar answered Jun 30 '26 06:06

constt