Containerize Python Application(Flask) using Docker
2 min readJan 15, 2021
Prerequisites:
- You must have docker installed on your machine (https://docs.docker.com/engine/install/)
- Docker must be up and running
- You must have docker-compose installed on your machine (https://docs.docker.com/compose/install/)
Step-1
- we have a Flask app(app.py) that runs on port 5000
- Now we are going to create requirements.txt. The place where we are going to note all our python modules to install in the container.
Note: You can also generate requiremens.txt using the below command-
pip freeze > requirements.txt
Step-2
- Let's create a Dockerfile that contains only 4 lines of code
Line 1:- “FROM python”
- this line commands to pull the latest python image. https://hub.docker.com/_/python
Line 2:- “WORKDIR /app”
- Declaring working directory
Line 3:- “COPY . .”
- By this, all the data present in the current directory will be copied to WORDIR.
Line 4:- “RUN pip install -r requirements.txt”
- Installing all our modules that are present in the requirements.txt.
Warning:-
For external Visibility, we have to make sure “host=’0.0.0.0'”
app.run(host=’0.0.0.0', port=5000)
Now you can build — “docker build -t dockerName .”
Run — “docker run -p 5000:5000 dockerName”
Step-3(Optional)
- Create docker-compose.yml
Run — “docker-compose up ”
Now the flask is running at “http://localhost:5000/”.