Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set/get variables in docker-compose.yml files?

I want to have a variable in a docker-compose.yml for my project that represents a port and instead of putting 8080 everywhere in the file, I'd rather use it as a variable.

Is it possible to set variable, say in the beginning of the file, then reuse it in other places of the file?

like image 708
Sergei Basharov Avatar asked Jan 04 '23 08:01

Sergei Basharov


2 Answers

You can use an external .env file and include it in the docker-compose file.

$ cat .env
port=8080

$ cat docker-compose.yml
version: '3'
services:
  web:
    port: "${port}"

docker-compose.yml and .env should be in the same directory.

like image 153
Luminance Avatar answered Jan 13 '23 11:01

Luminance


Starting from version 3.4, you can re-use configuration parts using extension fields. Valid extension fields have two requirements:

  1. Should be located at the root of your Compose file.
  2. Their name starts with the "x-" character sequence.

Here's an example:

version: '3.4'
x-logging:
  &default-logging
  options:
    max-size: '12m'
    max-file: '5'
  driver: json-file

services:
  web:
    image: myapp/web:latest
    logging: *default-logging
  db:
    image: mysql:latest
    logging: *default-logging
like image 39
Mustapha Hadid Avatar answered Jan 13 '23 12:01

Mustapha Hadid