How to use Docker Image for Horizontal Scaling In Docker
We can horizontally scale an application using docker swarm. Docker swarm is a cluster management and orchestration feature embedded in Docker. It allows running multiple containers across a cluster of nodes. To enable docker swarm in your machine run the below command :
docker swarm init
Now to create containers and deploy them using Swarm we need to create a docker-compose file, which is the deployment file. In the YAML file, we define the service, the container that the service should use, and also the number of containers in that image. that should be running.
Create a file name docker-compose.yml in the scaling directory and copy and paste the below code in it:
version: ‘3.8’
services:
web:
image: flaskapi
ports:
– 8000:5000
deploy:
replicas : 3
The docker-compose file defines the following thing:
- Version: the version of the compose file.
- Services: info about the services.
- Web: name of the service.
- Image: flaskapi is the image used for the web service.
- Ports: mapping local port to container port.
- Replicas: the number of containers to run.
Now to deploy the above file you can run the below command :
docker stack deploy my-stack -c docker-compose.yml
Above command will start 3 docker containers each running the flaskapi image.
Now you can scale the flask API by increasing the number of containers running the flaskapi image using the below command :
docker service scale my-stack_web=5
After running the above command 5 containers will be running the flaskapi image.
How to Use Docker Images For Scaling Applications?
Docker image is a lightweight piece of software that includes everything that your application needs to run, it includes code, software packages, and libraries. Docker images are built using a Docker file which includes the instruction for creating the image. The Docker image is built on top of a base image which is specified on top of the Dockerfile.
Docker images are typically stored in the docker registry such as the DockerHub, or Artifactory. Dockerfile is a source code for Docker images.