Flask Python Tutorial

Configure Docker for Flask Application

Posted on

Docker – a leading software container platform—can simplify the overall application delivery experience by providing a common platform for collaboration. Docker integrates seamlessly with existing tool chains, making it easier to deliver software rapidly.
Without Docker, there will be so much difficulty in development environment, because every programmer has different environment. Docker simplify that by contain application inside virtual machine technology. So, when distributed it will have the same environment.

Now, Let’s get started.

Install Docker

Docker can run in multiple operating system. Go to docker website to install which suitable with your system.
For windows, follow this steps:

https://docs.docker.com/docker-for-windows/install/#start-docker-for-windows

Create necessary files for Docker

Now, you will need to create a dockerfile called Dockerfile, docker-compose.yml, and requirements.txt in root directory of your projects, and write this snippets below.
Dockerfile file:

FROM python:2.7-alpineMAINTAINER WahyuENV INSTALL_PATH /web_appRUN mkdir -p $INSTALL_PATHWORKDIR $INSTALL_PATHCOPY requirements.txt requirements.txtRUN pip install -r requirements.txtCOPY . .CMD gunicorn -b 0.0.0.0:8000 --access-logfile - "web_app.app:create_app()"

I make a web_app folder to reference all of projects files. And start gunicorn to serve our Python app on port 8000.

docker-compose.yml

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

A service definition contains configuration that is applied to each container started for that service, much like passing command-line parameters to docker container create

requirements.txt

flaskgunicorn

This file required to list any package that we will include in our docker image.

Modify your main app file
My main app file named app.py

from flask import Flaskdef create_app():    app = Flask(__name__)    @app.route('/')    def index():        return 'Halo Flask. This is hot reload!!!'    @app.route('/about')    def about():        return 'About Me'    return app

See the difference of the last line with our previous first flask application projects.

Run docker image

Now, run docker image using this command:
You need an elevated administration to run the command

In linux:

sudo docker-compose up --build

In windows:
Make sure you already run docker for windows in the background.
Note: Make sure your Windows environment already configured to develop with docker such as set COMPOSE_CONVERT_WINDOWS_PATHS=1, etc.

docker-compose up --build

Now, test it using your browser to:

http://localhost:8000

It’s done. Simple right 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *