Setting up Docker
As our application grows into having multiple layers, such as a database, coupling the application into a single piece enables us to deploy our application. We’ll be using Docker to containerize our application layers into a single image, which can then be easily deployed locally or in the cloud.
Additionally, using a Dockerfile and a docker-compose file eliminates the need to upload and share images of our applications. New versions of our applications can be built from the Dockerfile and deployed using the docker-compose file. Application images can also be stored and retrieved from Docker Hub. This is known as a push and pull operation.
To begin setting up, download and install Docker from https://docs.docker.com/install.
Dockerfile
A Dockerfile contains instructions on how our application image is to be built. The following is an example Dockerfile:
FROM PYTHON:3.8 # Set working directory to /usr/src/app WORKDIR /usr/src/app # Copy the contents of the current local directory into the container's working directory ADD . /usr/src/app # Run a command CMD ["python", "hello.py"]
Next, we’ll build the application container image and tag it getting_started
as follows:
$ docker build -t getting_started .
If the Dockerfile isn’t present in the directory where the command is being run, the path to the Dockerfile should be properly appended as follows:
$ docker build -t api api/Dockerfile
The container image can be run using the following command:
$ docker run getting-started
Docker is an efficient tool for containerization. We have only looked at the basic operations and we’ll learn more operations practically in Chapter 9, Deploying FastAPI Applications.