Running Flask on Docker

Yora Radityohutomo
2 min readMar 31, 2018

--

Flask is the lightweight web framework in python. Flask can be used easily to create API or simple web application. Once you have done create your flask application in your local machine, you have to deploy it to the server. Sometimes it feels so painful to make sure your application can run smoothly in the server just because you have different environment on your local. But with Docker, you can fix the problem.

image from https://codefresh.io/docker-tutorial/hello-whale-getting-started-docker-flask/

So, what is Docker actually? Docker is the platform to enable developer help devops to build, ship and run the application. Docker exist as virtual machine that can containerized your application. It means all your dependency included in simple distributed configuration.

First you need to install docker, you can follow here based on your operating system. And then you need to install docker compose to simplify defining and running multi docker container, you can follow this instruction.

Create a project directory, as the example I create “flask_docker_demo”.

mkdir flask_docker_demo
cd flask_docker_demo

You need to specify list of python modules in requirements.txt file in your project directory. Just fill with flask and gunicorn for minimal requirements.

Create new folder to store all your python code, I create web_app folder. Then create app.py inside of web_app and add the following code.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
return "Hello World!!"

And the last, you need to create Dockerfile and docker-compose.yml outside the web_app folder. Here is code inside Dockerfile.

FROM python:2.7-slim
MAINTAINER Yora Radityohutomo <yoratyo@gmail.com>

RUN
apt-get update && apt-get install -qq -y \
build-essential libpq-dev --no-install-recommends

ENV INSTALL_PATH /web_app
RUN mkdir -p $INSTALL_PATH

WORKDIR
$INSTALL_PATH

COPY
requirements.txt requirements.txt
RUN pip install -r requirements.txt

COPY . .

CMD gunicorn -b 0.0.0.0:8000 --access-logfile - "web_app.app:app"

And following code inside docker-compose.yml.

version: '2'

services:
web_app:
build:
.
command: >
gunicorn -b 0.0.0.0:8000
--access-logfile -
--reload
"web_app.app:app"
environment:
PYTHONUNBUFFERED: 'true'
volumes:
- '.:/web_app'
ports:
- '8000:8000'

To build and run the application you can execute this command on your terminal inside the project directory.

docker-compose up --build

You can test it by opening this url in the browser.

localhost:8000

Congratulation you have done your first simple flask application using docker. Its very simple right? You can clone the example project from my github. Happy coding..

--

--