A few weeks ago I posted Step by step: ASP.NET Core on Docker were I showed how to build and run a Docker image with an ASP.NET Core application.
Today I bring you: Step by step: Scale ASP.NET Core with Docker Swarm so you can scale out or in the same application .
Assuming you have Docker 1.12 or later installed and running, follow this steps:
1. Create a dockerfile
On your Docker box create a dockerfile with the following contents
1 # We use the microsoft/dotnet image as a starting point. 2 FROM microsoft/dotnet 3 4 # Install git 5 RUN apt-get install git -y 6 7 # Create a folder to clone our source code 8 RUN mkdir repositories 9 10 # Set our working folder 11 WORKDIR repositories 12 13 # Clone the source code 14 RUN git clone https://github.com/cmendible/aspnet-core-helloworld.git 15 16 # Set our working folder 17 WORKDIR aspnet-core-helloworld/src/dotnetstarter 18 19 # Expose port 5000 for the application. 20 EXPOSE 5000 21 22 # Restore nuget packages 23 RUN dotnet restore 24 25 # Start the application using dotnet!!! 26 ENTRYPOINT dotnet run
2. Create a Docker image
With the dockerfile in place run the following command
1sudo docker build -t hello_world .
Now you have an image named hello_world with all the dependencies and code needed to run the sample.
3. Initialize a Swarm
Initialize Docker Swarm.
1docker swarm init
4. Create a Docker Service
Now that you have setup everything use the following command to create a service named hello_service based on the hello_world image and start it
1docker service create --name hello_service --publish 5000:5000 hello_world
Wait a few seconds and navigate to http://localhost:5000 and you should be able to reach the web application.
If you want to learn more about Docker services, start here: Service Create/
5. Scale up your application
Let’s scale your service up to 3 instances with the following command
1docker service scale hello_service=3
If you want to see how many replicas your service is running issue the following command:
1docker service ls
Note that it takes some seconds before all new replicas start.
6. Scale down your application
Let’s scale your service down to 1 instance with the following command
1docker service scale hello_service=1
7. Optional: Remove the service
If you are don’t want the service anymore, remove it from the Swarm with the following command
1docker service rm hello_service
You can get a copy of the docker file here: https://github.com/cmendible/dotnetcore.samples/tree/main/docker.helloworld
Hope it helps!