How to dockerize your WordPress website – part 2
What is a serviceSimply, a service is a group of containers sharing the same image & tag. For example, we can have a service called "web" which is a container of Nginx image.
How to create a serviceFirst login to manager1 in the swarm we created:
docker-machine ssh manager1We will create a service called "web" which is an Nginx container and expose port 80/tcp in it.
docker service create --name web --replicas 2 -p 80:80Now let's dive into the command above:
- docker service create, this is pretty forward, we are instructing docker to create a new service.
- --name parameter gives our service a human friendly name, in this case "web".
- --replicas , specifies the number of containers that should be launched
- -p, specifies which ports of the container should be published on the swarm, <target-port>:<service-port> for example 8080:80 is instructing docker to listen on the container port 80 and publish it to port 8080.
docker service ls
ID NAME REPLICAS IMAGE COMMAND ctolq1t4h2o8 web 0/2 nginxTo check on what nodes this service is published, we can use the following command:
docker service ps web
This shows us that some containers are running, and some are still preparing.Wait for a few minutes and all containers should be up and running.
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR web.1 nginx worker1 Running Preparing 2 minutes ago web.2 nginx manager1 Running Running 22 seconds ago
How to access services
A service can be accessed by navigating to the manager or workers I.P address. Try the I.P address of any of the nodes in your browser, you should see Nginx welcome page.
Scaling a serviceThe purpose of this command is to scale up or down depending on the needs and load of you application. Let's assume that our website has gone very slow because of high traffic and we need to spin up 2 more nginx containers
docker service scale web=4This command will spawn to new containers for the service web.
docker service lsshould indicate that we have 4 replicas of "web"
ID NAME REPLICAS IMAGE COMMAND ctolq1t4h2o8 web 4/4 nginx
The same concept can be applied to scaling down your application. For example the 2 containers you created above were only to handle high traffic during a certain time and you don't need them anymore, all what you have to do is to scale down the "web" service.
docker service scale web=2
Deleting a service
This is a simple command, all what you have to do is to specify the service name:
docker service rm web
We have seen how simple yet powerful docker swam is, in the next part we will go through more advanced topics and apply to a real world scenario (a WordPress website with a custom theme)