1

In the programming language we can define and declare a variable and use it later in the program, can we do same in docker-compose file?

For example in Java:

int x = 100; System.out.println("Number is: "+ x);
Similarly, in docker-compose file, can we declare a local variables and use it later.

docker-compose file

In the docker-compose file we want to declare tomcat_home as a variable and use it later as shown in example.

values: - tomcat_home: "/usr/local/tomcat"

# Creating Tomcat Server 1

Server1: image: tomcat hostname: TomcatServer1 container_name: TomcatServer1 volumes: - ${PWD}/tomcat-users.xml:${tomcat_home}/conf/tomcat-users.xml - ${PWD}/server.xml:${tomcat_home}/conf/server.xml

1

https://docs.docker.com/compose/environment-variables/#the-env-file

One could set a variable in an .env file:

TAG=1.2.3

and call it in a docker-compose file

docker-compose.yml

version: "3"
services:
  web:
    image: nginx:${TAG}
    ports:
    - 80:80

docker-compose up

returns:

Pulling web (nginx:1.2.3)...
ERROR: manifest for nginx:1.2.3 not found

No need to run docker-compose to check the config

According to the documentation one could run:

docker-compose config

to verify the docker-compose config

networks: {}
services:
  web:
    image: nginx:1.2.3
    ports:
    - 80:80/tcp
version: '3.0'
volumes: {}
1

For docker-compose, you can use either the environment or a .env file. For swarm mode, you can only use the environment. So for portability, I like to export variables into the shell or environment of the command being run.

From a bash shell, this would look like:

$ export tomcat_home=/usr/local/tomcat
$ docker-compose up

Depending on what you use to deploy your containers (shell script, custom code, some other CI/CD tool), exporting your environment variable will vary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.