Docker-compose Build Args in docker-compose.yaml
We can make the docker-compose file more generic by passing a build argument to it.
contents of app.py
import os
import time
import redis
from flask import Flask
app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)
def get_hit_count():
retries = 5
while True:
try:
return cache.incr('hits')
except redis.exceptions.ConnectionError as exc:
if retries == 0:
raise exc
retries -= 1
time.sleep(0.5)
@app.route('/')
def hello():
count = get_hit_count()
return 'Hello World! I have been seen {} times.\n'.format(count)
if __name__ == "__main__":
app.run(host="0.0.0.0")
contents of requirements.txt
flask
redis
contents of docker-compose.yaml. let's understand the argument along with other options in the docker-compose file.
version: '3'
services:
web:
build:
context: .
dockerfile: Dockerfile
args:
- PYTHON_VERSION=3.4
image: python-redis-2
ports:
- "5000:5000"
redis:
image: "redis:alpine"
Context : It is used to specify the directory where the docker file resides.
Dockerfile: Specifies the name of the docker file.
Args: It is the main parameter that will specify the python version, which Dockerfile should read and use it accordingly.
Image: It is the same as explained earlier.
Docker file:
#FROM python:3.4-alpine
ARG PYTHON_VERSION
FROM python:$PYTHON_VERSION
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
Here, in the above docker file ARG PYTHON_VERSION is the parameter which the docker file will read from docker-compose file and based on it,it will use the python image.