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.
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
.env fileDB_PORT=3306
.env fileDB_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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With