running flask app inside docker


running flask app inside docker

Docker is container platform is used by hundreds of develops and system admins to build, share and run applications. Let's get started with docker and running a simple flask application using the docker.

Installing docker in ubuntu using snap or apt

To install the docker using snap then run the below command

sudo snap install docker --classic

or

To install the docker using snap then run the below command

sudo apt-get install docker

Test the installation of docker using below command

docker --version

If docker installed sucessfully in your system then output looks like below.

 Docker version 18.06.1-ce, build e68fc7a

Create a simple flask application

Let's create new directory named "my_flask_app". Inside that directory create file named "app.py".
# my_flaskapp/app.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello Flask App!'

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

To test the app functionality run the command "python app.py" and access url "http://localhost:5000".

Let's add the requirements to the app.
# my_flaskapp/requirements.txt

Flask==1.1.1

Create "Dockerfile" to containerize the flask app

my_flaskapp/Dockerfile

FROM python:3
RUN mkdir /app
WORKDIR /app
COPY . /app
RUN pip install -r requirements.txt
EXPOSE 5000
CMD [ "python", "app.py", "0.0.0.0:5000"]

In the above docker file we have added instruction for docker to build the docker image. These are the steps defined in the dockerfile

  • Install the python3 environment
  • Create a directory "/app" in docker image
  • Change directory to "/app" inside docker image
  • Copy current directory of host to "/app" directory in the docker image
  • Run the command "pip install -r requirements.txt"
  • Expose port "5000" to host system from the docker
  • Run the command "python app.py 0.0.0.0:5000"

Build the docker image using the dockerfile

To build the docker image run the below command

sudo docker build -t my_flaskapp:latest .

To create container from the docker image run the below command

sudo docker run -p 5000:5000 -d my_flaskapp:latest

Now, access the url "http://localhost:5000" to confirm the running of the application.

Reference: https://docs.docker.com/get-started/  

Support Me on Patreon
Blog Archive