First make sure docker is installed in your machine and you have necessary permissions to execute the following commands in your system. If you want to know about basics of docker please refer my previous blog - Docker guide for beginners
Following sample files are available in this github repo
Step 1 : Create working directory
mkdir flask-helloworld cd flask-helloworld
Step 2: create following files inside the working directory
requirements.txt
Flask
app.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host='0.0.0.0')
Dockerfile
# base image
FROM python:3-onbuild
# specify the port that container should expos
EXPOSE 5000
# run the application
CMD ["python", "./app.py"]
Step 3 : Build and Run your container
Build docker image:
Following command read your Dockerfile and build your custom images. Go to the path where your Docker file locates and execute following command.
docker build -t <imagename>:<tag-name> <path of your dockerfile>
docker build -t sample-app:v1 .
final dot(.) specifies the current directory. -t specifies the tag name of the image
Listing docker images:
docker images
docker images -a
Running Docker container:
Docker run command is used to run a image inside the container. If the specified image available in local machine docker will take it from local or it will download from dockerhub and then store it to local machine.
docker container run <image-name>
docker container run sample-app:v1
It will create a new container and run the sample-app image inside the container.
If you want to execute the container in background use --detach (or) -d flag. It will detach the process from foreground and allow us to execute it into background. It will return the unique container id.
docker container run -p 5000:5000 -d sample-app:v1
Executing commands inside the container:
Following command allow us to login inside the container. It is very helpful to debug our application if something went wrong. we can execute linux commands inside the container
docker run -it <image-name> sh
docker run -it sample-app:v1 sh
Stop the container:
Following command used to stop the container.
docker container stop 9a425901d134
Deleting containers:
Every run docker creating new containers so it will eat disk space, so best practice is cleanup the containers once done with that.