Docker Swarm services
Published: 2022-03-16 10:57:16

**Docker Swarm Commands**

```
docker swarm init --advertise-addr <ip-addr>
docker service ls
docker service ps <name>
docker service create <name> <image-name>
docker service rm <name>
docker service scale <name>=5
docker swarm leave --force
docker node ls
docker node ps
docker node rm <id>
```

Create three virtual machines using vagrant(managenode,node1,node2).

```
# -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# This defines the version of vagrant
Vagrant.configure("2") do |config|

MACHINE = ["managenode","node1","node2"]
N = 2

(0..N).each do |i|

  config.vm.define "#{MACHINE[i]}" do |node|
  node.vm.hostname = MACHINE[i]
  node.vm.box = "ubuntu/focal64"
  node.vm.network :private_network, ip: "192.168.33.#{10+i}"

  node.vm.provider "virtualbox" do |vb|
  vb.memory = "1500"
  end

  node.vm.provision "shell", inline: <<-SHELL
     apt update -y
     apt install apt-transport-https ca-certificates -y
     curl software-properties-common
     curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -
     add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable"
     apt-cache policy docker-ce
     apt install docker-ce -y
     SHELL


end
end
end

```
Login managenode and initialize docker swarm

```
sudo docker swarm init --advertise-addr <ip-addr of server>
```
Now you will receive docker swarm join token address.Copy and paste it node1 and node2

```
docker swarm join --token <join-token> <ipaddr:port number>
```
Now you can see the created nodes from managenode using the command below.

```
docker node ls
```
**create an image**

Create a dockerfile for Apache webserver and Copy the Index.html

Make a directory
mkdir /test
cd /test
Create a sample web page with name index.html
vim /test/index.html

```
<!DOCTYPE html>
<html>
<body>

<h1>Hello World</h1>

<p>My Personal website</p>

</body>
</html>
```
Now create a file dockerfile
vim /test/dockerfile

```
FROM ubuntu
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update
RUN apt-get install apache2 -y
RUN apt-get install apache2-utils -y
RUN apt-get clean
COPY index.html /var/www/html/
EXPOSE 80
CMD ["apache2ctl","-D","FOREGROUND"]
```
Next step is to build the docker file by using the docker build command.

```
sudo docker build -t myapachewebserver .
```

**Create Service**

```
docker service create --name "Apachewebserver" -p 8080:80 myapachewebserver
```
To list services
```
docker service ls
```
To list task of services
```
docker service ps Apachewebserver
```
Now you can browse the webserver 

http://ipaddress-of-managenode:8080
http://ipaddress-of-node1:8080
http://ipaddress-of-node2:8080

Here if any of the node terminated, the service would disturb in that node.If node1 is down then we wouldnot get the webserver through http://ipaddress-of-node1:8080.

To remove service 

```
docker service rm Apachewebserver
```
If any of the node terminated, the service wouldnot disturbed if you use "--mode global" 

```
docker service create --name "Apachewebserver" -p 8080:80 --mode global myapachewebserver
```

If you want to make replica you can use command shown below

```
docker service rm Apachewebserver

docker service create --name "Apachewebserver" -p 8080:80 --replica 2 myapachewebserver
```
Here managenode will select the best performing node from the node1 and node2 along with managenode.

Now you can browse the webserver 

http://ipaddress-of-managenode:8080
http://ipaddress-of-node1:8080
http://ipaddress-of-node2:8080

you can check the services by using the command shown below

```
docker node ps
docker service ps Apachewebserver
docker service ls
```
you can check whether the containers present or not  by using the command shown below

```
docker ps
```
So here we could see the Apachewebserver container only in managenode and any one of the nodes(node1 and node2).


**Scaling**

You can scale the service by using the command shown below.

```
docker service scale Apachewebserver=5
docker service ps Apachewebserver
```
you could see 5 copies of Apachewebserver.Managenode will disrtibute the service according to the best performing nodes like  managenode,2 node1 and 2 node2.

If you want to drain the service you can use the command below.

```
docker node update --availability drain managenode
docker service ps Apachewebserver
docker node ls
```
Now your managenode availability got drained and an additional node will be created.Now managenode has no power to scale up and down the services.Use the below command to retain the power of managenode.

```
docker node update --availability active managenode
```
**Docker Swarm Service using overlay network demo**

First remove the service 

```
docker service rm Apachewebserver
```
create an apache service

```
docker service create --name Apache2 --mode global -d -p 8003:80 httpd

docker service ls
docker service ps Apache2
```
Now you can browse the webserver 

http://ipaddress-of-managenode:8003
http://ipaddress-of-node1:8003
http://ipaddress-of-node2:8003

Create a overlay network

```
docker network create -d overlay myoverlay1
```
Lets create a web application using php and mysql.we can pull a sample application from hshar/webapp and create a service out of it.

```
docker service create --name webapp1 -d --network myoverlay1 -p 8001:80 hshar/webapp

docker service ls
docker service ps Apache2
```
create a service for mysql

```
docker service create --name mysql -d --network myoverlay1 -p 3306:3306 hshar/mysql:5.5

docker service ls
docker service ps mysql
```
Managenode will distribute the webapp1 and myql in different nodes
as part of load balancing.

Login to the node that containing webapp1 and enter into container to modify the webapp1.

```
docker ps
docker exec -it <containerID> bash
nano /var/www/html/index.php

<html>
<head>
<title>Docker Sample App</title>

<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$servername = "mysql";
$username = "root";
$password = "edureka";
$dbname = "docker";
$name=$_POST["name"];
$phone=$_POST["phone"];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO emp (name, phone)
VALUES ('".$name."', '".$phone."')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
}
?>
</head>
<body>
        <form action="index.php" method="POST">
                <input type="text" name="name">
                <input type="text" name="phone">
                <input type="submit" name="submit">
        </form>
</body>
</html>

exit
```
Login to the node that containing mysql and enter into container to modify the mysql.

```
docker ps
docker exec -it <containerID> bash

echo $MYSQL_ROOT_PASSWORD
mysql -u root -pedureka
CREATE DATABASE docker;
USE docker;
CREATE TABLE emp(name VARCHAR(15),phone VARCHAR(12));
exit

exit
```
Now you can browse the webserver 

http://ipaddress-of-managenode:8001
http://ipaddress-of-node1:8001
http://ipaddress-of-node2:8001

Add the name and phone.Now you can see the name and phone in table "emp" of database "docker" in mysql.

```
docker exec -it <containerID> bash

mysql -u root -pedureka
USE docker;
show tables;
select * from emp;
exit

exit

```
To leave node from docker swarm 

```
docker swarm leave
```
After a node leaves the swarm, you can run the docker node rm command on a manager node to remove the node from the node list.

```
docker node rm <nodename>
```