Docker Healthcheck

HEALTHCHECK

The HEALTHCHECK instruction has two forms:

HEALTHCHECK [OPTIONS] CMD command (check container health by running a command inside the container)
HEALTHCHECK NONE (disable any healthcheck inherited from the base image)
The HEALTHCHECK instruction tells Docker how to test a container to check that it is still working. This can detect cases such as a web server that is stuck in an infinite loop and unable to handle new connections, even though the server process is still running.

States in healthcheck: starting, healthy, unhealthy.
It expects only 0 (healthy) or 1 (unhealthy), not any other exit code.

When a container has a healthcheck specified, it has a health status in addition to its normal status. This status is initially starting. Whenever a health check passes, it becomes healthy (whatever state it was previously in). After a certain number of consecutive failures, it becomes unhealthy.

The options that can appear before CMD are:

--interval=DURATION (default: 30s)
--timeout=DURATION (default: 30s)
--start-period=DURATION (default: 0s)
--retries=N (default: 3)
The health check will first run interval seconds after the container is started, and then again interval seconds after each previous check completes.

If a single run of the check takes longer than timeout seconds then the check is considered to have failed.

It takes retries consecutive failures of the health check for the container to be considered unhealthy.

start period provides initialization time for containers that need time to bootstrap. Probe failure during that period will not be counted towards the maximum number of retries. However, if a health check succeeds during the start period, the container is considered started and all consecutive failures will be counted towards the maximum number of retries.

There can only be one HEALTHCHECK instruction in a Dockerfile. If you list more than one then only the last HEALTHCHECK will take effect.

The command after the CMD keyword can be either a shell command (e.g. HEALTHCHECK CMD /bin/check-running) or an exec array (as with other Dockerfile commands; see e.g. ENTRYPOINT for details).

The command’s exit status indicates the health status of the container. The possible values are:

0: success - the container is healthy and ready for use
1: unhealthy - the container is not working correctly
2: reserved - do not use this exit code
For example, to check every five minutes or so that a web-server is able to serve the site’s main page within three seconds:

HEALTHCHECK --interval=5m --timeout=3s \
  CMD curl -f http://localhost/ || exit 1
To help debug failing probes, any output text (UTF-8 encoded) that the command writes on stdout or stderr will be stored in the health status and can be queried with docker inspect. Such output should be kept short (only the first 4096 bytes are stored currently).

When the health status of a container changes, a health_status event is generated with the new status.

The HEALTHCHECK feature was added in Docker 1.12.

SHELL
SHELL ["executable", "parameters"]
The SHELL instruction allows the default shell used for the shell form of commands to be overridden. The default shell on Linux is ["/bin/sh", "-c"], and on Windows is ["cmd", "/S", "/C"]. The SHELL instruction must be written in JSON form in a Dockerfile.

The SHELL instruction is particularly useful on Windows where there are two commonly used and quite different native shells: cmd and powershell, as well as alternate shells available including sh.

-bash-4.2$ sudo docker run --health-cmd="curl -f localhost:9200/_cluster/health || false" --health-interval=5s \
> --health-retries=3 --health-timeout=2s --health-start-period=15s elasticsearch:2


-bash-4.2$ sudo docker container run --name p2 -d --health-cmd="pg_isready -U postgres || exit 1" postgres
Unable to find image 'postgres:latest' locally
latest: Pulling from library/postgres
000eee12ec04: Already exists
7b8ef50e8d64: Pull complete
304f7c67e7db: Pull complete
9fe4298c8c65: Pull complete
f1ca857656d1: Pull complete
95d6c34812f7: Pull complete
9436c546bd1d: Pull complete
922326a079d9: Pull complete
d6e9dcf0d140: Pull complete
83ac3914c283: Pull complete
5ffbf9359c6e: Pull complete
d280abe82126: Pull complete
f5a37695fe7e: Pull complete
233830cd10db: Pull complete
Digest: sha256:c4da9c62c26179440d5dc7409cb7db60f4a498f0f2c080b97fdb9f7ec0b3502b
Status: Downloaded newer image for postgres:latest
c9a16a0c495b8ac490a20b152708f12083fb44fa19533c14b84d961219c2cd89
-bash-4.2$


CONTAINER ID        IMAGE                                          COMMAND                  CREATED             STATUS                             PORTS                NAMES
c9a16a0c495b        postgres                                       "docker-entrypoint.s…"   30 seconds ago      Up 28 seconds (health: starting)   5432/tcp             p2


-bash-4.2$ docker container ls
CONTAINER ID        IMAGE                                          COMMAND                  CREATED             STATUS                    PORTS                NAMES
c9a16a0c495b        postgres                                       "docker-entrypoint.s…"   37 seconds ago      Up 35 seconds (healthy)   5432/tcp             p2


-bash-4.2$ docker container inspect p2

                "Log": [
                    {
                        "Start": "2019-12-08T22:21:54.022705241-05:00",
                        "End": "2019-12-08T22:21:54.686401553-05:00",
                        "ExitCode": 0,
                        "Output": "/var/run/postgresql:5432 - accepting connections\n"
                    }
                ]

-bash-4.2$ time sudo docker service create --name service1 postgres
m3cxvzjf5uljpou6bsdz5sa6h
overall progress: 1 out of 1 tasks
1/1: running   [==================================================>]
verify: Service converged

real    0m10.598s
user    0m0.110s
sys     0m0.068s
-bash-4.2$ time sudo docker service create --name service2 --health-cmd="pg_isready -U postgres || exit 1" postgres
4uc6320kaqr6hjq2bihzdtsud
overall progress: 1 out of 1 tasks
1/1: running   [==================================================>]
verify: Service converged

real    0m42.315s
user    0m0.360s
sys     0m0.098s
-bash-4.2$

-bash-4.2$ docker service ls
ID                  NAME                 MODE                REPLICAS            IMAGE                                          PORTS

m3cxvzjf5ulj        service1             replicated          1/1                 postgres:latest                         
4uc6320kaqr6        service2             replicated          1/1                 postgres:latest            

Docker Resource Requirements

Resource Requirements:


• docker run has many options, service create has different options
• Set at service create/update, but are controlled per-container
• Set for CPU and memory, reserving and limiting
• Maximum given to container
• --limit-cpu .5
• --limit-memory 256M
• Beware of OOME (with or without limits) 
• Minimum free needed to schedule container (Swarm keeps track)
• --reserve-cpu .5
• --reserve-memory 256M
• Reserve cpu and memory
# docker service create --reserve-memory 800M --reserve-cpu 1 mysql
• Limit cpu and memory
# docker service create --limit-memory 150M --limit-cpu .25 nginx
• Service update is the same
• Remove them with update to 0
# docker service update --limit-memory 0 --limit-cpu 0 myservice


be careful on limits of memory. if container uses more then limit, it'll crash
better then letting node OOM take down random process


RESOURCES:

https://hub.docker.com/r/shaan2212/stress/

Lets say you have three nodes, each with 1G and 1 CPU in each
docker service create --reserve-memory=800M --name 800 nginx
docker service create --reserve-memory=300M --replicas=4 --name 300 nginx
notice how none of the 2nd can run on node of the first
docker service inspect 800
remove reservation
docker service update --reserve-memory=0 800
docker service inspect 800
what happens when more reserve then you have?
docker service create --reserve-cpu=8 --name 8 nginx
what happens when we run over memory limits?
docker service create --limit-memory 100M --name 100 shaan2212/stress
docker service logs 100
docker service rm 100

Docker Node Availability

Node Availability:


Each node can have one of three admin-controlled states.
Only affects if existing or new containers can run on that node.
active: Run existing tasks, available for new tasks.
pause: run existing tasks, not available for new tasks (good for troubleshooting).
drain: Reschedules existing tasks, not available for new tasks (good for maintenance).

Remember this affects service updates and recovering tasks too. (coz pause node will not get updates).

Internet examples include "drain managers", but not realistic.
Use labels to control manager tasks.


$ docker service create --name webapp1 --replicas 5 nginx
m7ui7ag3uo2aaufotyio6qenh
overall progress: 5 out of 5 tasks
1/5: running   [==================================================>]
2/5: running   [==================================================>]
3/5: running   [==================================================>]
4/5: running   [==================================================>]
5/5: running   [==================================================>]
verify: Service converged
[node1] (local) root@192.168.0.18 ~
$ docker node update --availability=pause node2
node2
[node1] (local) root@192.168.0.18 ~
$ docker service update --replicas=8 webapp1
webapp1
overall progress: 8 out of 8 tasks
1/8: running   [==================================================>]
2/8: running   [==================================================>]
3/8: running   [==================================================>]
4/8: running   [==================================================>]
5/8: running   [==================================================>]
6/8: running   [==================================================>]
7/8: running   [==================================================>]
8/8: running   [==================================================>]
verify: Service converged



$ docker service ps webapp1
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE           ERROR               PORTS
ft1wqc61o3hi        webapp1.1           nginx:latest        node2               Running             Running 6 minutes ago                     
lnf2rwag2jo2        webapp1.2           nginx:latest        node4               Running             Running 6 minutes ago                     
hx6n4s6bb8qa        webapp1.3           nginx:latest        node3               Running             Running 6 minutes ago                     
tqfl72at9t0i        webapp1.4           nginx:latest        node1               Running             Running 6 minutes ago                     
78oo6fg7r4mi        webapp1.5           nginx:latest        node2               Running             Running 6 minutes ago                     
eaxitdw33il4        webapp1.6           nginx:latest        node4               Running             Running 3 minutes ago                     
gfyjptl0t2ox        webapp1.7           nginx:latest        node3               Running             Running 3 minutes ago                     
zox95qoaxm0k        webapp1.8           nginx:latest        node1               Running             Running 3 minutes ago                     
[node1] (local) root@192.168.0.18 ~


[node1] (local) root@192.168.0.18 ~
$ docker node update --availability=drain node3
node3
[node1] (local) root@192.168.0.18 ~
$ docker service ps webapp1
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE            ERROR               PORTS
ft1wqc61o3hi        webapp1.1           nginx:latest        node2               Running             Running 8 minutes ago                       
lnf2rwag2jo2        webapp1.2           nginx:latest        node4               Running             Running 8 minutes ago                       
slghwoni1emi        webapp1.3           nginx:latest        node2               Running             Running 1 second ago                       
hx6n4s6bb8qa         \_ webapp1.3       nginx:latest        node3               Shutdown            Shutdown 2 seconds ago                     
tqfl72at9t0i        webapp1.4           nginx:latest        node1               Running             Running 8 minutes ago                       
78oo6fg7r4mi        webapp1.5           nginx:latest        node2               Running             Running 8 minutes ago                       
eaxitdw33il4        webapp1.6           nginx:latest        node4               Running             Running 5 minutes ago                       
al3psy95sg1b        webapp1.7           nginx:latest        node4               Running             Running 1 second ago                       
gfyjptl0t2ox         \_ webapp1.7       nginx:latest        node3               Shutdown            Shutdown 2 seconds ago                     
zox95qoaxm0k        webapp1.8           nginx:latest        node1               Running             Running 5 minutes ago                       
[node1] (local) root@192.168.0.18 ~
$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
rpi7zm6f58bsg27flw5r5zn61 *   node1               Ready               Active              Leader              19.03.4
uv3t4tfdeiwuf93456h3xl1is     node2               Ready               Active                                  19.03.4
4axpu998jh7jx6t38d6jwccwj     node3               Ready               Drain                                   19.03.4
ebyyc6z1b9unw7231g9hp7b5k     node4               Ready               Active                                  19.03.4
[node1] (local) root@192.168.0.18 ~
$

[node1] (local) root@192.168.0.18 ~
$ docker node update --availability=active node3
node3
[node1] (local) root@192.168.0.18 ~
$


[node1] (local) root@192.168.0.18 ~
$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
rpi7zm6f58bsg27flw5r5zn61 *   node1               Ready               Active              Leader              19.03.4
uv3t4tfdeiwuf93456h3xl1is     node2               Ready               Active                                  19.03.4
4axpu998jh7jx6t38d6jwccwj     node3               Ready               Active                                  19.03.4
ebyyc6z1b9unw7231g9hp7b5k     node4               Ready               Active                                  19.03.4
[node1] (local) root@192.168.0.18 ~
$


$ 

Service Placement Preference

Service Placement Preference:


• 17.04+ feature for a best effort "soft requirement"
• Only one strategy for now, "spread"
• Spreads tasks among all values of a Label
• Good to ensure distribution across availability zones, datacenters, racks, subnets, etc.
• Works on service create and update
• Can add multiple preferences for multi-layer placement control
• Won't move service tasks if labels change
• Use with Constraints if labels aren't on all nodes
• "missing label is the same as having the label with a null value".


node1 : azone=1
node2 : azone=2
node3 : azone=2
node4 : azone=4

[node1] (local) root@192.168.0.18 ~
$ docker node update --label-add azone=1 node1
node1
[node1] (local) root@192.168.0.18 ~
$ docker node update --label-add azone=2 node2
node2
[node1] (local) root@192.168.0.18 ~
$ docker node update --label-add azone=2 node3
node3
[node1] (local) root@192.168.0.18 ~
$ docker node update --label-add azone=4 node4
node4


$ docker service create --placement-pref=spread=node.labels.azone --replicas 3 --name webapp nginx
1uh1h61biwapz4yj2bmobfo43
overall progress: 3 out of 3 tasks
1/3: running   [==================================================>]
2/3: running   [==================================================>]
3/3: running   [==================================================>]
verify: Service converged
[node1] (local) root@192.168.0.18 ~
$ docker service create --placement-pref=spread=node.labels.azone --replicas 3 --name webapp2 nginx
ryan0nrv0hhcxvr6b79eksuw7
overall progress: 3 out of 3 tasks
1/3: running   [==================================================>]
2/3: running   [==================================================>]
3/3: running   [==================================================>]
verify: Service converged


$ docker service ls
ID                  NAME                 MODE                REPLICAS            IMAGE                             PORTS
jqty4aqkzr9j        voteapp_visualizer   replicated          1/1                 dockersamples/visualizer:stable   *:8080->8080/tcp
1uh1h61biwap        webapp               replicated          3/3                 nginx:latest                     
ryan0nrv0hhc        webapp2              replicated          3/3                 nginx:latest                   

$ docker service update --placement-pref-rm spread=node.labels.azone webapp
webapp
overall progress: 3 out of 3 tasks
1/3: running   [==================================================>]
2/3: running   [==================================================>]
3/3: running   [==================================================>]
verify: Service converged
[node1] (local) root@192.168.0.18 ~
$ docker service scale webapp2=8
webapp2 scaled to 8
overall progress: 8 out of 8 tasks
1/8: running   [==================================================>]
2/8: running   [==================================================>]
3/8: running   [==================================================>]
4/8: running   [==================================================>]
5/8: running   [==================================================>]
6/8: running   [==================================================>]
7/8: running   [==================================================>]
8/8: running   [==================================================>]
verify: Service converged
[node1] (local) root@192.168.0.18 ~
$ docker service ps webapp2
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE            ERROR               PORTS
y5clpspcpchy        webapp2.1           nginx:latest        node2               Running             Running 9 minutes ago                       
qum8jp6oveqa        webapp2.2           nginx:latest        node4               Running             Running 9 minutes ago                       
phyzxk1bnoiw        webapp2.3           nginx:latest        node1               Running             Running 9 minutes ago                       
v4jlc775ed8b        webapp2.4           nginx:latest        node3               Running             Running 43 seconds ago                     
yyl2n0ojztzh        webapp2.5           nginx:latest        node2               Running             Running 43 seconds ago                     
rd70bjdcfulu        webapp2.6           nginx:latest        node4               Running             Running 43 seconds ago                     
u0ns4sl7dvm7        webapp2.7           nginx:latest        node1               Running             Running 43 seconds ago                     
nlt9z441f1ye        webapp2.8           nginx:latest        node1               Running             Running 43 seconds ago                     
[node1] (local) root@192.168.0.18 ~
$ docker service ps webapp
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE           ERROR               PORTS
qthwd10gi59d        webapp.1            nginx:latest        node1               Running             Running 9 minutes ago                     
t4kejf5ltpo5        webapp.2            nginx:latest        node4               Running             Running 9 minutes ago                     
rti00fkfw0zm        webapp.3            nginx:latest        node3               Running             Running 9 minutes ago                     
[node1] (local) root@192.168.0.18 ~


$ docker service update --constraint-add node.role==worker webapp2
webapp2
overall progress: 8 out of 8 tasks
1/8: running   [==================================================>]
2/8: running   [==================================================>]
3/8: running   [==================================================>]
4/8: running   [==================================================>]
5/8: running   [==================================================>]
6/8: running   [==================================================>]
7/8: running   [==================================================>]
8/8: running   [==================================================>]
verify: Service converged
[node1] (local) root@192.168.0.18 ~
$ docker service ps webapp2
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE            ERROR               PORTS
y5clpspcpchy        webapp2.1           nginx:latest        node2               Running             Running 14 minutes ago                     
qum8jp6oveqa        webapp2.2           nginx:latest        node4               Running             Running 14 minutes ago                     
iojpx0f7dllr        webapp2.3           nginx:latest        node4               Running             Running 3 minutes ago                       
phyzxk1bnoiw         \_ webapp2.3       nginx:latest        node1               Shutdown            Shutdown 3 minutes ago                     
v4jlc775ed8b        webapp2.4           nginx:latest        node3               Running             Running 6 minutes ago                       
yyl2n0ojztzh        webapp2.5           nginx:latest        node2               Running             Running 6 minutes ago                       
rd70bjdcfulu        webapp2.6           nginx:latest        node4               Running             Running 6 minutes ago                       
lpwd56h4b7gq        webapp2.7           nginx:latest        node4               Running             Running 3 minutes ago                       
u0ns4sl7dvm7         \_ webapp2.7       nginx:latest        node1               Shutdown            Shutdown 3 minutes ago                     
oyobxn8q447e        webapp2.8           nginx:latest        node3               Running             Running 3 minutes ago                       
nlt9z441f1ye         \_ webapp2.8       nginx:latest        node1               Shutdown            Shutdown 3 minutes ago                     
[node1] (local) root@192.168.0.18 ~
$

Placement Preferences in Stack Files:


version : "3.1"
services:
   web:
    image: nginx
    deploy:
     placement:
      preferences:
       spread:node:labels:azone


Deleting service and labels:



[node1] (local) root@192.168.0.18 ~
$ docker service rm webapp webapp2
webapp
webapp2
[node1] (local) root@192.168.0.18 ~
$ docker node update --label-rm=azone node1
node1
[node1] (local) root@192.168.0.18 ~
$ docker node update --label-rm=azone node2
node2
[node1] (local) root@192.168.0.18 ~
$ docker node update --label-rm=azone node3
node3
[node1] (local) root@192.168.0.18 ~
$ docker node update --label-rm=azone node4
node4
[node1] (local) root@192.168.0.18 ~
$

Docker Service Modes

Service Modes:


1. Notice it in docker service ls
2. Defaults to replicated, but global is an option.
3. Global=one task per node
4. Set on service create only, must remove service to change.
5. Good for host agents (security, monitoring, backup, proxy, etc).
6. Global Mode can be combined with constraints. (version 1.13+)


Replicated v/s global services:

There are two types of service deployments, replicated and global.

For a replicated service, you specify the number of identical tasks you want to run. For example, you decide to deploy an HTTP service with three replicas, each serving the same content.

A global service is a service that runs one task on every node. There is no pre-specified number of tasks. Each time you add a node to the swarm, the orchestrator creates a task and the scheduler assigns the task to the new node. Good candidates for global services are monitoring agents, an anti-virus scanners or other types of containers that you want to run on every node in the swarm.


[node1] (local) root@192.168.0.48 ~/voting-app/example-voting-app
$ docker service create --mode=global --name=test1 nginx
u2dxb2rmibqce20eg40gcqs9o
overall progress: 4 out of 4 tasks
przg4018ytv0: running   [==================================================>]
epr99u2uuky4: running   [==================================================>]
ptncdjhii2as: running   [==================================================>]
khlavmixa3pv: running   [==================================================>]
verify: Service converged

[node1] (local) root@192.168.0.48 ~/voting-app/example-voting-app
$ docker service ls
ID                  NAME                 MODE                REPLICAS            IMAGE                             PORTS
u2dxb2rmibqc        test1                global              4/4                 nginx:latest                     
q9vom02oh95n        voteapp_visualizer   replicated          1/1                 dockersamples/visualizer:stable   *:8080->8080/tcp
[node1] (local) root@192.168.0.48 ~/voting-app/example-voting-app

$ docker service ps test1
ID                  NAME                              IMAGE               NODE                DESIRED STATE       CURRENT STATE           
ERROR               PORTS
1vfev5nr30mh        test1.przg4018ytv0ksr3fqsvvkcst   nginx:latest        node4               Running             Running 31 seconds ago 
                   
dgk73ddgd6im        test1.epr99u2uuky4temuxydo1j98x   nginx:latest        node3               Running             Running 31 seconds ago 
                   
129pvl9sspag        test1.khlavmixa3pvam8x8okpiv84v   nginx:latest        node2               Running             Running 31 seconds ago 
                   
ov2k20yegep0        test1.ptncdjhii2as07utv3m51a6zr   nginx:latest        node1               Running             Running 30 seconds ago                     
[node1] (local) root@192.168.0.48 ~/voting-app/example-voting-app
$
[node1] (local) root@192.168.0.48 ~/voting-app/example-voting-app
$

[node1] (local) root@192.168.0.48 ~/voting-app/example-voting-app

$ docker service rm test1
test1
[node1] (local) root@192.168.0.48 ~/voting-app/example-voting-app

$ docker service ls
ID                  NAME                 MODE                REPLICAS            IMAGE                             PORTS
q9vom02oh95n        voteapp_visualizer   replicated          1/1                 dockersamples/visualizer:stable   *:8080->8080/tcp
[node1] (local) root@192.168.0.48 ~/voting-app/example-voting-app

$ docker service create --mode=global --name=test1 --constraint=node.role==worker nginx
8i78qliotelyddf5l7kgc7hwt
overall progress: 3 out of 3 tasks
przg4018ytv0: running   [==================================================>]
khlavmixa3pv: running   [==================================================>]
epr99u2uuky4: running   [==================================================>]
verify: Service converged

[node1] (local) root@192.168.0.48 ~/voting-app/example-voting-app

$ docker service ls
ID                  NAME                 MODE                REPLICAS            IMAGE                             PORTS
8i78qliotely        test1                global              3/3                 nginx:latest                     
q9vom02oh95n        voteapp_visualizer   replicated          1/1                 dockersamples/visualizer:stable   *:8080->8080/tcp
[node1] (local) root@192.168.0.48 ~/voting-app/example-voting-app

$ docker service ps test1
ID                  NAME                              IMAGE               NODE                DESIRED STATE       CURRENT STATE            ERROR               PORTS
lnu4c4mxrftk        test1.przg4018ytv0ksr3fqsvvkcst   nginx:latest        node4               Running             Running 33 seconds ago                     
jg75f1seauxg        test1.epr99u2uuky4temuxydo1j98x   nginx:latest        node3               Running             Running 33 seconds ago                     
6loqrzvminzx        test1.khlavmixa3pvam8x8okpiv84v   nginx:latest        node2               Running             Running 33 seconds ago                     
[node1] (local) root@192.168.0.48 ~/voting-app/example-voting-app
$ 

Controlling Container Placements


* By default a swarm service spreads its tasks out over Nodes.Try's to use the least-used Node for a task.
* Swarm has multiple ways to control which node a container runs on.
* Can be used togther for complex requirements.
1. Node Labels plus service contraints ( <key>=<value> )
2. Service Modes (replicated|global)
3. (new in 17.04+) Placement Preferences (spread)
4. Node Availability (active|pause|drain)
5. Resource Requirements (cpu|memory)


Service Constraints:


-bash-4.2$ docker service create --name app1 --constraint node.role==worker nginx
i342kxxhjqvp3js26v7a3ha4j
overall progress: 1 out of 1 tasks
1/1: running   [==================================================>]
verify: Service converged

-bash-4.2$ docker service ps app1
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE            ERROR               PORTS
29jycn7bjrib        app1.1              nginx:latest        worker2             Running             Running 38 seconds ago


-bash-4.2$ docker service update --constraint-rm node.role==worker --constraint-add node.role==manager app1
app1
overall progress: 1 out of 1 tasks
1/1: running   [==================================================>]
verify: Service converged
-bash-4.2$ docker service ps app1
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE             ERROR               PORTS
r9auvuykv2j2        app1.1              nginx:latest        manager             Running             Running 19 seconds ago
29jycn7bjrib         \_ app1.1          nginx:latest        worker2             Shutdown            Shutdown 20 seconds ago

-bash-4.2$ docker node update --label-add dmz=true worker2
worker2

-bash-4.2$ docker inspect worker2
[
    {
        "ID": "p5k4qztbwe92rmq1ygdu9vqkk",
        "Version": {
            "Index": 622
        },
        "CreatedAt": "2019-12-02T06:35:12.002886593Z",
        "UpdatedAt": "2019-12-09T04:02:06.979884066Z",
        "Spec": {
            "Labels": {
                "dmz": "true"
            },



-bash-4.2$ docker service create --name dmz-nginx --constraint node.labels.dmz==true --replicas 2 nginx
jkhos0jc8z6t55v4zzhik1fyq
overall progress: 2 out of 2 tasks
1/2: running   [==================================================>]
2/2: running   [==================================================>]
verify: Service converged

-bash-4.2$ docker service ps dmz-nginx
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE            ERROR               PORTS
6bjm1tkdg5pl        dmz-nginx.1         nginx:latest        worker2             Running             Running 25 seconds ago
x8ljpqalykol        dmz-nginx.2         nginx:latest        worker2             Running             Running 25 seconds ago
-bash-4.2$


Built-in labels:


node.id (listed in docker node ls)
node.hostname (listed in docker node ls)
node.ip (eg. 172.19.17.0/24)
node.role (worker | manager)
node.platform.os (linux|windows|etc)
node.platform.arch (x86_64|arm64|386|etc)
node.labels (empty by default)

Cleaning up:


-bash-4.2$ docker service rm app1 dmz-nginx
app1
dmz-nginx
-bash-4.2$ docker service ls
ID                  NAME                 MODE                REPLICAS            IMAGE                             PORTS
j2nbudo31jhd        voteapp_visualizer   replicated          1/1                 dockersamples/visualizer:stable   *:8080->8080/tcp


-bash-4.2$ docker node update --label-rm dmz worker2
worker2
-bash-4.2$

Docker networking and Stacks

Explaining Docker Networking:


Docker networking is basically used to establish communication between the docker containers and the outside world via host machine or you can say it is a communication passage through which all the isolated containers communicate with each other in various situations to perform the required actions.

  • User-defined bridge networks are best when you need multiple containers to communicate on the same Docker host.
  • Host networks are best when the network stack should not be isolated from the Docker host, but you want other aspects of the container to be isolated.
  • Overlay networks are best when you need containers running on different Docker hosts to communicate, or when multiple applications work together using swarm services.
  • Macvlan networks are best when you are migrating from a VM setup or need your containers to look like physical hosts on your network, each with a unique MAC address.
  • Third-party network plugins allow you to integrate Docker with specialized network stacks.

Overlay Networking:


-bash-4.2$ docker network create --driver overlay mydrupal
p6wlckz3tpbsvrxg7vkscb3o5
-bash-4.2$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
b7fad9e8721f        bridge              bridge              local
630c7e7be1df        docker_gwbridge     bridge              local
8df84c6fceb2        host                host                local
oy1sf7s64vkh        ingress             overlay             swarm
p6wlckz3tpbs        mydrupal            overlay             swarm
913d04ce1d13        none                null                local

-bash-4.2$ docker service create --name psql --network mydrupal -e POSTGRES_PASSWORD=mypass postgres
7cxim9tpkhs528l10mvnkqvwg
overall progress: 1 out of 1 tasks
1/1: running   [==================================================>]
verify: Service converged

-bash-4.2$ docker service ps msql
no such service: msql

-bash-4.2$ docker service ps psql
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE            ERROR               PORTS
4aj11siw8gv3        psql.1              postgres:latest     worker2             Running             Running 17 seconds ago
-bash-4.2$ docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
7cxim9tpkhs5        psql                replicated          1/1                 postgres:latest
-bash-4.2$ docker service create --name drupal --network mydrupal -p 80:80 drupal
hyr5o861bdzk50s45bu8z52tv
overall progress: 1 out of 1 tasks
1/1: running
verify: Service converged
-bash-4.2$ docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
hyr5o861bdzk        drupal              replicated          1/1                 drupal:latest       *:80->80/tcp
7cxim9tpkhs5        psql                replicated          1/1                 postgres:latest
-bash-4.2$ docker service ps drupal
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE                ERROR               PORTS
t79l6b5y6han        drupal.1            drupal:latest       manager             Running             Running about a minute ago
-bash-4.2$

Routing Mesh: Global Traffic Router


1. Route ingress (incoming) packets for a service to proper Task.
2. Spans all nodes in Swarm
3. Uses IPVS from Linux Kernel.
4. Load balances Swarm Services across their Tasks.
5. Two ways this works:

i. Container to Container in a overlay network (Uses VIP).
ii. External traffic incoming to published ports (all nodes listen).

6. It is a stateless load balancing.
7. this LB is at OSI layer 3 (TCP), not layer 4 (DNS).
8. Both the limitations can overcome with:

Nginx or HAProxy LB proxy, or:
Docker Enterprise edition, which come with built-in L4 web proxy.


-bash-4.2$ docker service create --name search --replicas 3 -p 9200:9200 elasticsearch:2
rqvmbrn5d4rlsfir9sb2hv1w0
overall progress: 3 out of 3 tasks
1/3: running   [==================================================>]
2/3: running   [==================================================>]
3/3: running   [==================================================>]
verify: Service converged
-bash-4.2$ docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
hyr5o861bdzk        drupal              replicated          1/1                 drupal:latest       *:80->80/tcp
7cxim9tpkhs5        psql                replicated          1/1                 postgres:latest
rqvmbrn5d4rl        search              replicated          3/3                 elasticsearch:2     *:9200->9200/tcp
-bash-4.2$ docker service ps search
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE                ERROR               PORTS
yrxkktj47j05        search.1            elasticsearch:2     manager             Running             Running about a minute ago
fhvst8z2b8vo        search.2            elasticsearch:2     worker2             Running             Running 53 seconds ago
jwu0fld4om1t        search.3            elasticsearch:2     worker2             Running             Running 53 seconds ago
-bash-4.2$ ip r
default via 192.168.29.1 dev ens33 proto static metric 100
172.17.0.0/16 dev docker0 proto kernel scope link src 172.17.0.1
172.18.0.0/16 dev docker_gwbridge proto kernel scope link src 172.18.0.1
192.168.29.0/24 dev ens33 proto kernel scope link src 192.168.29.10 metric 100
-bash-4.2$
-bash-4.2$

-bash-4.2$ curl -v 192.168.29.10:9200
* About to connect() to 192.168.29.10 port 9200 (#0)
*   Trying 192.168.29.10...
* Connected to 192.168.29.10 (192.168.29.10) port 9200 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 192.168.29.10:9200
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=UTF-8
< Content-Length: 368
<
{
  "name" : "Maxwell Dillon",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "2iyfSDGNRq2EdxE1vWXHTA",
  "version" : {
    "number" : "2.4.6",
    "build_hash" : "5376dca9f70f3abef96a77f4bb22720ace8240fd",
    "build_timestamp" : "2017-07-18T12:17:44Z",
    "build_snapshot" : false,
    "lucene_version" : "5.5.4"
  },
  "tagline" : "You Know, for Search"
}
* Connection #0 to host 192.168.29.10 left intact
-bash-4.2$ curl -v 192.168.29.11:9200
* About to connect() to 192.168.29.11 port 9200 (#0)
*   Trying 192.168.29.11...
* Connected to 192.168.29.11 (192.168.29.11) port 9200 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 192.168.29.11:9200
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=UTF-8
< Content-Length: 368
<
{
  "name" : "Maxwell Dillon",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "2iyfSDGNRq2EdxE1vWXHTA",
  "version" : {
    "number" : "2.4.6",
    "build_hash" : "5376dca9f70f3abef96a77f4bb22720ace8240fd",
    "build_timestamp" : "2017-07-18T12:17:44Z",
    "build_snapshot" : false,
    "lucene_version" : "5.5.4"
  },
  "tagline" : "You Know, for Search"
}
* Connection #0 to host 192.168.29.11 left intact
-bash-4.2$ curl -v 192.168.29.12:9200
* About to connect() to 192.168.29.12 port 9200 (#0)
*   Trying 192.168.29.12...
* Connected to 192.168.29.12 (192.168.29.12) port 9200 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 192.168.29.12:9200
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=UTF-8
< Content-Length: 369
<
{
  "name" : "George Tarleton",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "0sXPGfTOQCCscT57rYUxxw",
  "version" : {
    "number" : "2.4.6",
    "build_hash" : "5376dca9f70f3abef96a77f4bb22720ace8240fd",
    "build_timestamp" : "2017-07-18T12:17:44Z",
    "build_snapshot" : false,
    "lucene_version" : "5.5.4"
  },
  "tagline" : "You Know, for Search"
}
* Connection #0 to host 192.168.29.12 left intact
-bash-4.2$


Stacks:


1. In 1.13 docker adds a new layer of abstraction to swarm called Stacks
2. Stacks accept Compose files as their declarative definition for services, networks, volumes.
3. We can "docker stack deploy" rather than "docker service create".
4. Stack manages all those objects for us, including overlay n/w per stack. Add stack name to start of their name.
5. new "deploy": key in compose file. Can't do build.
6. compose ignores "deploy"; swarm ignores "build".
7. docker-compose cli not needed on swarm server.


-bash-4.2$ git clone https://github.com/shaan2212/example-voting-app.git
fatal: could not create work tree dir 'example-voting-app'.: Permission denied
-bash-4.2$ sudo git clone https://github.com/shaan2212/example-voting-app.git
[sudo] password for dockmgr:
Cloning into 'example-voting-app'...
remote: Enumerating objects: 832, done.
remote: Total 832 (delta 0), reused 0 (delta 0), pack-reused 832
Receiving objects: 100% (832/832), 950.35 KiB | 356.00 KiB/s, done.
Resolving deltas: 100% (293/293), done.
-bash-4.2$ ls -l
total 4
drwxr-xr-x. 2 root root   40 Nov 30 08:21 customimage
drwxr-xr-x. 8 root root 4096 Dec  4 23:14 example-voting-app
-bash-4.2$
-bash-4.2$
-bash-4.2$ cd example-voting-app/
-bash-4.2$ ls -l
total 128
-rw-r--r--. 1 root root 54824 Dec  4 23:14 architecture.png
-rw-r--r--. 1 root root   808 Dec  4 23:14 docker-compose-javaworker.yml
-rw-r--r--. 1 root root   517 Dec  4 23:14 docker-compose-k8s.yml
-rw-r--r--. 1 root root   400 Dec  4 23:14 docker-compose-simple.yml
-rw-r--r--. 1 root root  1107 Dec  4 23:14 docker-compose-windows-1809.yml
-rw-r--r--. 1 root root   994 Dec  4 23:14 docker-compose-windows.yml
-rw-r--r--. 1 root root   821 Dec  4 23:14 docker-compose.yml
-rw-r--r--. 1 root root  1476 Dec  4 23:14 docker-stack-simple.yml
-rw-r--r--. 1 root root  1037 Dec  4 23:14 docker-stack-windows-1809.yml
-rw-r--r--. 1 root root  1284 Dec  4 23:14 docker-stack-windows.yml
-rw-r--r--. 1 root root  1707 Dec  4 23:14 docker-stack.yml
-rw-r--r--. 1 root root  2058 Dec  4 23:14 ExampleVotingApp.sln
-rw-r--r--. 1 root root  1182 Dec  4 23:14 Jenkinsfile
drwxr-xr-x. 2 root root   250 Dec  4 23:14 k8s-specifications
-rw-r--r--. 1 root root  3248 Dec  4 23:14 kube-deployment.yml
-rw-r--r--. 1 root root 10758 Dec  4 23:14 LICENSE
-rw-r--r--. 1 root root   185 Dec  4 23:14 MAINTAINERS
-rw-r--r--. 1 root root  3574 Dec  4 23:14 README.md
drwxr-xr-x. 6 root root   193 Dec  4 23:14 result
drwxr-xr-x. 5 root root   107 Dec  4 23:14 vote
drwxr-xr-x. 6 root root   149 Dec  4 23:14 worker
-bash-4.2$ vi docker-stack.yml
-bash-4.2$
-bash-4.2$ docker stack deploy -c docker-stack.yml voteapp
Creating network voteapp_frontend
Creating network voteapp_backend
Creating network voteapp_default
Creating service voteapp_result
Creating service voteapp_worker

Creating service voteapp_visualizer
Creating service voteapp_redis
Creating service voteapp_db
Creating service voteapp_vote
-bash-4.2$
-bash-4.2$ docker stack ls
NAME                SERVICES            ORCHESTRATOR
voteapp             6                   Swarm
-bash-4.2$ docker stack ps voteapp
ID                  NAME                   IMAGE                                          NODE                DESIRED STATE       CURRENT STATE              ERROR               PORTS
m3w89adon80k        voteapp_vote.1         dockersamples/examplevotingapp_vote:before     worker2             Running             Preparing 14 seconds ago
q9yhao2gjndd        voteapp_db.1           postgres:9.4                                   manager             Running             Preparing 24 seconds ago
uku8r4t3ryfu        voteapp_redis.1        redis:alpine                                   worker2             Running             Running 7 seconds ago
i333b3yqlkh7        voteapp_visualizer.1   dockersamples/visualizer:stable                manager             Running             Preparing 34 seconds ago
nqrffe2jyqcq        voteapp_worker.1       dockersamples/examplevotingapp_worker:latest   manager             Running             Preparing 42 seconds ago
718s5harqvxf        voteapp_result.1       dockersamples/examplevotingapp_result:before   manager             Running             Running 5 seconds ago
0s84riq1vmj8        voteapp_vote.2         dockersamples/examplevotingapp_vote:before     manager             Running             Preparing 14 seconds ago
-bash-4.2$ docker container ls
CONTAINER ID        IMAGE                                          COMMAND                  CREATED             STATUS              PORTS                NAMES
6dea2cc3e13b        dockersamples/examplevotingapp_result:before   "node server.js"         17 seconds ago      Up 15 seconds       80/tcp               voteapp_result.1.718s5harqvxfsqn7lumiuvsoz
ccf165bd59ee        elasticsearch:2                                "/docker-entrypoint.…"   22 minutes ago      Up 22 minutes       9200/tcp, 9300/tcp   search.1.yrxkktj47j05sqiwi9alyvrdg
954b383b5f72        drupal:latest                                  "docker-php-entrypoi…"   47 minutes ago      Up 47 minutes       80/tcp               drupal.1.t79l6b5y6hanwuv1f0ggfu1ep

-bash-4.2$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
b7fad9e8721f        bridge              bridge              local
630c7e7be1df        docker_gwbridge     bridge              local
8df84c6fceb2        host                host                local
oy1sf7s64vkh        ingress             overlay             swarm
p6wlckz3tpbs        mydrupal            overlay             swarm
913d04ce1d13        none                null                local
6uud58ijvggy        voteapp_backend     overlay             swarm
jrsobkuwnb7o        voteapp_default     overlay             swarm
ty2yifkoawhr        voteapp_frontend    overlay             swarm


-bash-4.2$ docker stack services voteapp
ID                  NAME                 MODE                REPLICAS            IMAGE                                          PORTS
6gq4smbw5sw4        voteapp_worker       replicated          1/1                 dockersamples/examplevotingapp_worker:latest
j2nbudo31jhd        voteapp_visualizer   replicated          1/1                 dockersamples/visualizer:stable                *:8080->8080/tcp
qkgi2jp3yqy4        voteapp_redis        replicated          1/1                 redis:alpine                           
rg04xelmvf39        voteapp_db           replicated          1/1                 postgres:9.4                           
tujsar2ocfhz        voteapp_result       replicated          1/1                 dockersamples/examplevotingapp_result:before   *:5001->80/tcp
tzejc82b0urb        voteapp_vote         replicated          2/2                 dockersamples/examplevotingapp_vote:before     *:5000->80/tcp

updated the replicas value to 5 from 2 and re-deployed it:

-bash-4.2$ docker stack deploy -c docker-stack.yml voteapp
Updating service voteapp_result (id: tujsar2ocfhzuh144944qnq4p)
Updating service voteapp_worker (id: 6gq4smbw5sw4dyvl5uroy1jpl)
Updating service voteapp_visualizer (id: j2nbudo31jhd6kyjt0b9pizn4)
Updating service voteapp_redis (id: qkgi2jp3yqy459bjsosivilpw)
Updating service voteapp_db (id: rg04xelmvf39sn85gga54gx0f)
Updating service voteapp_vote (id: tzejc82b0urb73vahqyx85ggu)


-bash-4.2$ docker stack services voteapp
ID                  NAME                 MODE                REPLICAS            IMAGE                                          PORTS
6gq4smbw5sw4        voteapp_worker       replicated          1/1                 dockersamples/examplevotingapp_worker:latest
j2nbudo31jhd        voteapp_visualizer   replicated          1/1                 dockersamples/visualizer:stable                *:8080->8080/tcp
qkgi2jp3yqy4        voteapp_redis        replicated          1/1                 redis:alpine                           
rg04xelmvf39        voteapp_db           replicated          1/1                 postgres:9.4                           
tujsar2ocfhz        voteapp_result       replicated          1/1                 dockersamples/examplevotingapp_result:before   *:5001->80/tcp
tzejc82b0urb        voteapp_vote         replicated          5/5                 dockersamples/examplevotingapp_vote:before     *:5000->80/tcp
-bash-4.2$

Installation of Jenkins on Linux and Deployment NGINX through Jenkins

Installation of Jenkins: [root@worker1 ~]# useradd -c "jenkins user" jenkins [root@worker1 ~]# passwd jenkins Changing passw...