Our Dockerfile:
FROM alpine
ADD script.sh /script.sh
CMD ["/bin/sh", "/script.sh"]
Our script.sh
#!/bin/sh
echo "Message: ${VAR_MESSAGE:-nothing_defined}"
When we build our image and run a container from that image without any variables set, we will expect Message: nothing_defined
$ docker build -f Dockerfile -t local:v1 .
$ docker run -it local:v1
Message: nothing_defined
When we pass the environment variable, we will see it in our output:
$ docker run -it -e VAR_MESSAGE=hello_world local:v1
Message: hello_world
Our docker-compose.yml
version: "3.7"
services:
hello:
build:
context: .
dockerfile: Dockerfile
environment:
- VAR_MESSAGE=hello_world
networks:
- hello
networks:
hello:
Building:
$ docker-compose build
Running:
$ docker-compose up 1 ↵
Creating network "aa_hello" with the default driver
Message: hello_world
Let's take a producer and consumer setup, where we will have 2 services defined in our compose, where they will work together.
We will have a shared volume and one container will write to the shared volume and the other container will read from that volume.
We also instruct our compose to only let the consumer container run after the producer has started.
Our Dockerfile for our producer: Dockerfile.producer
FROM alpine
ADD script.sh /script.sh
CMD ["/bin/sh", "/script.sh"]
Our Dockerfile for our consumer: Dockerfile.consumer
FROM alpine
CMD echo "reading from file -> $(cat /data/file.txt)"
The script that the producer will run:
#!/bin/sh
echo "writing to disk"
echo "Message: ${VAR_MESSAGE:-nothing_defined}" > /data/file.txt
Our docker-compose.yml
version: "3.7"
services:
producer:
build:
context: .
dockerfile: Dockerfile.producer
environment:
- VAR_MESSAGE=hello_world
volumes:
- shared_vol:/data
networks:
- hello
consumer:
build:
context: .
dockerfile: Dockerfile.consumer
volumes:
- shared_vol:/data
depends_on:
- producer
networks:
- hello
volumes:
shared_vol:
driver: local
networks:
hello:
Building and running our containers:
$ docker-compose build
$ docker-compose up
Creating network "aa_hello" with the default driver
Creating volume "aa_shared_vol" with local driver
Creating aa_producer_1 ... done
Creating aa_consumer_1 ... done
Attaching to aa_producer_1, aa_consumer_1
producer_1 | writing to disk
consumer_1 | reading from file -> Message: hello_world
aa_producer_1 exited with code 0
aa_consumer_1 exited with code 0