Run Simple Flask App using Docker Compose

In this tutorial you will learn how to create a simple Flask App and run it inside a docker container using docker Compose

Required Software

  • docker (1.6.0 or above)
  • docker-compose (1.3.1+)
  • python 2.7 or above
  • Linux VM - (We used ubuntu 14.04 64 bit)

Create the Flask App and Deployment files

Create a parent directory flask_compose_sample

$ mkdir flask_compose_sample
$ cd flask_compose_sample

Create a folder web. All our files for the flask app will be inside this directory.

$ mkdir web
$ cd web

Flask Application

Create a new file app.py inside web and add the following python code

From flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Flask Dockerized'

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0')

Requirements File

Requirements file states the software required to be installed in the container. Create a file requirements.txt inside web folder

Flask==0.10.1

Dockerfile

This file is needed to create a docker image and deploy it

FROM ubuntu:latest
MAINTAINER Rajdeep Dua "dua_rajdeep@yahoo.com"
RUN apt-get update -y
RUN apt-get install -y python-pip python-dev build-essential
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
ENTRYPOINT ["python"]
CMD ["app.py"]

Docker Compose File

Go to the parent directory flask_compose_sample and create a file docker-compose.yml. For each service there is a parent tag and child tags which specify

web

  • Builds from the Dockerfile in the current directory.
  • Forwards the exposed port 5000 on the container to port 5000 on the host machine..
  • Mounts the current directory on the host to /code inside the container allowing you to modify the code without having to rebuild the image.
web:
  build: ./web
  ports:
   - "5000:5000"
  volumes:
   - .:/code

Build and Run the Service using Docker Compose

Run the following command to build the docker image flask-sample-one from web directory and deploy is as a service

$ docker-compose up

You can go to the browser and open the url http://localhost:5000 to see the HTML rendered

../_images/flask_simple_app.png

You can find the container runtime details as shown below

$ docker ps -a
CONTAINER ID        IMAGE                              COMMAND                CREATED             STATUS                        PORTS                    NAMES

06351e6fa146 flaskcomposesample_web:latest “python app.py” 38 minutes ago Up 38 minutes 0.0.0.0:5000->5000/tcp flaskcomposesample_web_1 0.0.0.0:5000->5000/tcp clever_blackwell