Wolf Fact: Wolves were the first animals in the world to be placed on the U.S. Endangered Species Act list in 1973.
Prerequisites: C#, basic Web API, basic Docker, Visual Studio, and Docker Desktop
This is the 1st part of the series Microservices with Dapr. In the following article, I will demonstrate deploying a straightforward web API using a docker-compose file.
If you are already familiar with this, please check out the next articles in the series.
Docker-compose simplifies the creation of reproducible Docker containers by replacing lengthy Docker commands with a concise configuration file. Docker-compose is a YAML file. YAML is a file format for holding structured data, like JSON or XML. The YAML format is tab and space-sensitive. YAML is both computer-readable and human-readable.
Let’s now create a web API and a docker-compose file. The complete code can be found here.
1. A New Web API Project
Due to enabled Docker support, Visual Studio automatically generates a Dockerfile. This file contains instructions for creating a container specific to the project. We will use this Dockerfile with a docker-compose file to deploy the project.
The auto-generated Dockerfile treats the solution folder as the root directory. So we will place our Docker compose file in the solution folder. To avoid making any changes in this docker file, and to keep things simpler.
2. Docker-Compose file
Create a docker-compose.yaml file. Write the code shown below in the file.
There are various instructions in this file, let’s understand them one by one.
“version:” — Compose file is using docker-compose file format 3.0
“services:” — All the services that need to be deployed are listed here. ( I have only one in this case.)
“dockerapp:” — Desired service name for a project.
“image:” — Docker image name
If we run project from Visual Studio we can see running containers in the Docker desktop.
“ports”:- It is used to define the mapping between the host server and the Docker container.
CONTAINER_PORT is used for applications running inside the docker container and HOST_PORT is to allow external access to container resources.
CONTAINER_PORT will be the same as Dockerfile’s expose port. Any available port can be used as HOST_PORT. That’s How we create a simple docker-compose file.
Now, Let's do the same using the docker-compose file. Open the cmd with the docker-compose file in the scope.
Only three simple commands are needed for this process.
To build a docker image
docker compose build
To deploy the container.
docker compose up
And when we don’t need the running container anymore.
docker compose down
We can access the API like this and verify our code.
That’s how we can deploy a simple web API using docker-compose. Don't hesitate to comment. Thank you.