How Do You Create Your Own Dockerfile to Create a Flask Application?

Problem scenario
You want to use Flask inside a Docker container.  You want to build your own image for the Docker container.  How do you create your own Dockerfile to create a Flask application?

Solution
Prerequisite

Install Docker.  See this posting if you need directions.

Procedures
1.  Create a Dockerfile with the following content (you may want to replace "16.04" with "latest" and if you want to change the location of where the .py file is, that may or may not be troublesome):

FROM ubuntu:16.04  

RUN apt-get update
RUN apt-get install -y python3 python-pip
RUN apt-get clean all

RUN pip install flask

ADD hello.py /tmp/hello.py

EXPOSE 5000

CMD ["python","/tmp/hello.py"]  

2.  In the directory that the Dockerfile will go, create a file called hello.py with the following content:

from flask import Flask
app = Flask(__name__)

@app.route('/hi')
def hello_world():
    return 'Hello World!'

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

3.  Run this command in the directory with the above files:

docker build -t flask .

(On a server with .5 GB of RAM and 1 shared vCPU, this can take 20 minutes.)

4.  Then run this command:  docker run -d -P flask

5.  Test it from the Docker host.  Run this command:  docker ps -a

Find the result for a recently created container.  The "PORTS" column should have a mapping to the port 5000.  Use the non-5000 port (in the output of the command above) and construct this Linux command below (but replace xxxxx with that port number in the following draft of a command):

curl http://localhost:xxxxx/hi

6.  Run the curl command above once you substitute the xxxxx.  You should see "Hello World!"

Leave a comment

Your email address will not be published.