Impiegazione Blue-Green à i salari minimi

In questu articulu avemu usatu bash, ssh, docker и nginx Urganizeremu un layout senza saldatura di l'applicazione web. Impiegazione blu-verde hè una tecnica chì permette di aghjurnà istantaneamente una applicazione senza rifiutà una sola dumanda. Hè una di e strategie di implementazione di zero downtime è hè megliu adattatu per l'applicazioni cù una sola istanza, ma a capacità di carricà una seconda istanza pronta per eseguisce vicinu.

Diciamu chì avete una applicazione web cù quale parechji clienti sò attivamente travagliendu, è ùn ci hè assolutamente micca manera per ch'ellu si stende per un paru di sicondi. È avete veramente bisognu di lancià un aghjurnamentu di a biblioteca, una correzione di bug, o una nova funzione fresca. In una situazione nurmale, vi tuccherà à piantà l 'applicazzioni, rimpiazzà lu è principiatu di novu. In u casu di docker, pudete prima rimpiazzà, poi riavvia, ma ci sarà sempre un periodu in quale e dumande à l'applicazione ùn saranu micca trattate, perchè di solitu l'applicazione richiede un pocu di tempu per caricare inizialmente. E s'ellu principia, ma diventa inoperabile? Questu hè u prublema, risolvemu cù i mezi minimi è u più eleganti pussibule.

DISCLAIMER: A maiò parte di l'articulu hè presentatu in un formatu sperimentale - in a forma di una registrazione di una sessione di cunsola. Spergu chì questu ùn serà micca troppu difficiule à capisce è u codice si documentarà abbastanza. Per l'atmosfera, imaginate chì questi ùn sò micca solu snippets di codice, ma carta da un teletipu "di ferru".

Impiegazione Blue-Green à i salari minimi

Tecniche interessanti chì sò difficiuli di Google solu per leghje u codice sò descritte à u principiu di ogni sizzioni. Se qualcosa altru ùn hè chjaru, google è verificate. spiegà shell (furtunatamente, funziona di novu, per via di u sbloccamentu di u telegramma). Se ùn pudete micca Google nunda, dumandate in i cumenti. Seraghju felice di aghjunghje à a sezione currispundente "Tecniche interessanti".

Cuminciamu.

$ mkdir blue-green-deployment && cd $_

sirvizziu

Facemu un serviziu sperimentale è mette in un cuntainer.

Tecniche interessanti

  • cat << EOF > file-name (Quì Documentu + Redirezione I/O) hè un modu per creà un schedariu multi-linea cù un cumandamentu. Tuttu u bash leghje da /dev/stdin dopu à sta linea è prima di a linea EOF sarà registratu in file-name.
  • wget -qO- URL (spiegà shell) - output un documentu ricevutu via HTTP à /dev/stdout (analogicu curl URL).

Stampata

Aghju specificamente rottu u snippet per attivà l'evidenziazione per Python. À a fine ci sarà un altru pezzu cusì. Cunsiderate chì in questi lochi a carta hè stata tagliata per esse mandata à u dipartimentu di evidenziazione (induve u codice era culurita à manu cù evidenziatori), è dopu sti pezzi sò stati incollati.

$ cat << EOF > uptimer.py
from http.server import BaseHTTPRequestHandler, HTTPServer
from time import monotonic

app_version = 1
app_name = f'Uptimer v{app_version}.0'
loading_seconds = 15 - app_version * 5

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            try:
                t = monotonic() - server_start
                if t < loading_seconds:
                    self.send_error(503)
                else:
                    self.send_response(200)
                    self.send_header('Content-Type', 'text/html')
                    self.end_headers()
                    response = f'<h2>{app_name} is running for {t:3.1f} seconds.</h2>n'
                    self.wfile.write(response.encode('utf-8'))
            except Exception:
                self.send_error(500)
        else:
            self.send_error(404)

httpd = HTTPServer(('', 8080), Handler)
server_start = monotonic()
print(f'{app_name} (loads in {loading_seconds} sec.) started.')
httpd.serve_forever()
EOF

$ cat << EOF > Dockerfile
FROM python:alpine
EXPOSE 8080
COPY uptimer.py app.py
CMD [ "python", "-u", "./app.py" ]
EOF

$ docker build --tag uptimer .
Sending build context to Docker daemon  39.42kB
Step 1/4 : FROM python:alpine
 ---> 8ecf5a48c789
Step 2/4 : EXPOSE 8080
 ---> Using cache
 ---> cf92d174c9d3
Step 3/4 : COPY uptimer.py app.py
 ---> a7fbb33d6b7e
Step 4/4 : CMD [ "python", "-u", "./app.py" ]
 ---> Running in 1906b4bd9fdf
Removing intermediate container 1906b4bd9fdf
 ---> c1655b996fe8
Successfully built c1655b996fe8
Successfully tagged uptimer:latest

$ docker run --rm --detach --name uptimer --publish 8080:8080 uptimer
8f88c944b8bf78974a5727070a94c76aa0b9bb2b3ecf6324b784e782614b2fbf

$ docker ps
CONTAINER ID        IMAGE               COMMAND                CREATED             STATUS              PORTS                    NAMES
8f88c944b8bf        uptimer             "python -u ./app.py"   3 seconds ago       Up 5 seconds        0.0.0.0:8080->8080/tcp   uptimer

$ docker logs uptimer
Uptimer v1.0 (loads in 10 sec.) started.

$ wget -qSO- http://localhost:8080
  HTTP/1.0 503 Service Unavailable
  Server: BaseHTTP/0.6 Python/3.8.3
  Date: Sat, 22 Aug 2020 19:52:40 GMT
  Connection: close
  Content-Type: text/html;charset=utf-8
  Content-Length: 484

$ wget -qSO- http://localhost:8080
  HTTP/1.0 200 OK
  Server: BaseHTTP/0.6 Python/3.8.3
  Date: Sat, 22 Aug 2020 19:52:45 GMT
  Content-Type: text/html
<h2>Uptimer v1.0 is running for 15.4 seconds.</h2>

$ docker rm --force uptimer
uptimer

Proxy inversu

Per chì a nostra applicazione pò cambià inosservata, hè necessariu chì ci sia una altra entità davanti à ellu chì ammucciarà a so sustituzione. Puderia esse un servitore web nginx в modalità proxy inversa. Un proxy inversu hè stabilitu trà u cliente è l'applicazione. Accetta e richieste da i clienti è li trasmette à l'applicazione è trasmette e risposte di l'applicazione à i clienti.

L'applicazione è u proxy inversu ponu esse ligati in docker usendu rete docker. Cusì, u cuntinuu cù l'applicazione ùn hà mancu bisognu di rinvià un portu nantu à u sistema di l'ospite; questu permette chì l'applicazione sia massimamente isolata da e minacce esterne.

Se u proxy inversu vive nantu à un altru òspite, duverete abbandunà a reta di docker è cunnette l'applicazione à u proxy inversu attraversu a reta di l'ospite, trasmettendu u portu. Apps paràmetru --publish, cum'è à u primu principiu è cum'è cù u proxy inversu.

Eseguiremu u proxy inversu in u portu 80, perchè questu hè esattamente l'entità chì deve esse à sente a reta esterna. Se u portu 80 hè occupatu nantu à u vostru òspite di teste, cambia u paràmetru --publish 80:80 nantu --publish ANY_FREE_PORT:80.

Tecniche interessanti

Stampata

$ docker network create web-gateway
5dba128fb3b255b02ac012ded1906b7b4970b728fb7db3dbbeccc9a77a5dd7bd

$ docker run --detach --rm --name uptimer --network web-gateway uptimer
a1105f1b583dead9415e99864718cc807cc1db1c763870f40ea38bc026e2d67f

$ docker run --rm --network web-gateway alpine wget -qO- http://uptimer:8080
<h2>Uptimer v1.0 is running for 11.5 seconds.</h2>

$ docker run --detach --publish 80:80 --network web-gateway --name reverse-proxy nginx:alpine
80695a822c19051260c66bf60605dcb4ea66802c754037704968bc42527bf120

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS              PORTS                NAMES
80695a822c19        nginx:alpine        "/docker-entrypoint.…"   27 seconds ago       Up 25 seconds       0.0.0.0:80->80/tcp   reverse-proxy
a1105f1b583d        uptimer             "python -u ./app.py"     About a minute ago   Up About a minute   8080/tcp             uptimer

$ cat << EOF > uptimer.conf
server {
    listen 80;
    location / {
        proxy_pass http://uptimer:8080;
    }
}
EOF

$ docker cp ./uptimer.conf reverse-proxy:/etc/nginx/conf.d/default.conf

$ docker exec reverse-proxy nginx -s reload
2020/06/23 20:51:03 [notice] 31#31: signal process started

$ wget -qSO- http://localhost
  HTTP/1.1 200 OK
  Server: nginx/1.19.0
  Date: Sat, 22 Aug 2020 19:56:24 GMT
  Content-Type: text/html
  Transfer-Encoding: chunked
  Connection: keep-alive
<h2>Uptimer v1.0 is running for 104.1 seconds.</h2>

Impiegazione perfetta

Lancemu una nova versione di l'applicazione (cun ​​​​un impulsu duppiu di u rendimentu di l'iniziu) è pruvate à implementà senza soluzione.

Tecniche interessanti

  • echo 'my text' | docker exec -i my-container sh -c 'cat > /my-file.txt' - Scrivite u testu my text à schedariu /my-file.txt in u cuntainer my-container.
  • cat > /my-file.txt - Scrivite u cuntenutu di l'input standard in un schedariu /dev/stdin.

Stampata

$ sed -i "s/app_version = 1/app_version = 2/" uptimer.py

$ docker build --tag uptimer .
Sending build context to Docker daemon  39.94kB
Step 1/4 : FROM python:alpine
 ---> 8ecf5a48c789
Step 2/4 : EXPOSE 8080
 ---> Using cache
 ---> cf92d174c9d3
Step 3/4 : COPY uptimer.py app.py
 ---> 3eca6a51cb2d
Step 4/4 : CMD [ "python", "-u", "./app.py" ]
 ---> Running in 8f13c6d3d9e7
Removing intermediate container 8f13c6d3d9e7
 ---> 1d56897841ec
Successfully built 1d56897841ec
Successfully tagged uptimer:latest

$ docker run --detach --rm --name uptimer_BLUE --network web-gateway uptimer
96932d4ca97a25b1b42d1b5f0ede993b43f95fac3c064262c5c527e16c119e02

$ docker logs uptimer_BLUE
Uptimer v2.0 (loads in 5 sec.) started.

$ docker run --rm --network web-gateway alpine wget -qO- http://uptimer_BLUE:8080
<h2>Uptimer v2.0 is running for 23.9 seconds.</h2>

$ sed s/uptimer/uptimer_BLUE/ uptimer.conf | docker exec --interactive reverse-proxy sh -c 'cat > /etc/nginx/conf.d/default.conf'

$ docker exec reverse-proxy cat /etc/nginx/conf.d/default.conf
server {
    listen 80;
    location / {
        proxy_pass http://uptimer_BLUE:8080;
    }
}

$ docker exec reverse-proxy nginx -s reload
2020/06/25 21:22:23 [notice] 68#68: signal process started

$ wget -qO- http://localhost
<h2>Uptimer v2.0 is running for 63.4 seconds.</h2>

$ docker rm -f uptimer
uptimer

$ wget -qO- http://localhost
<h2>Uptimer v2.0 is running for 84.8 seconds.</h2>

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS              PORTS                NAMES
96932d4ca97a        uptimer             "python -u ./app.py"     About a minute ago   Up About a minute   8080/tcp             uptimer_BLUE
80695a822c19        nginx:alpine        "/docker-entrypoint.…"   8 minutes ago        Up 8 minutes        0.0.0.0:80->80/tcp   reverse-proxy

À questu stadiu, l'imaghjini hè custruitu direttamente nantu à u servitore, chì esige chì e fonti di l'applicazioni sò quì, è ancu carica u servitore cù un travagliu innecessariu. U prossimu passu hè di assignà l'assemblea di l'imaghjini à una macchina separata (per esempiu, à un sistema CI) è poi trasfiriri à u servitore.

Trasferimentu d'imaghjini

Sfortunatamente, ùn hà micca sensu di trasfiriri l'imaghjini da localhost à localhost, cusì sta sezione pò esse esplorata solu s'ellu avete dui ospiti cù Docker in manu. À u minimu, pare qualcosa cusì:

$ ssh production-server docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

$ docker image save uptimer | ssh production-server 'docker image load'
Loaded image: uptimer:latest

$ ssh production-server docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
uptimer             latest              1d56897841ec        5 minutes ago       78.9MB

squadra docker save salva i dati di l'imaghjini in un archiviu .tar, vale à dì chì pesa circa 1.5 volte più di quellu chì pesa in forma compressa. Allora scuzzulemu in nome di risparmià tempu è trafficu:

$ docker image save uptimer | gzip | ssh production-server 'zcat | docker image load'
Loaded image: uptimer:latest

Pudete ancu monitorà u prucessu di scaricamentu (ancu se questu richiede una utilità di terzu):

$ docker image save uptimer | gzip | pv | ssh production-server 'zcat | docker image load'
25,7MiB 0:01:01 [ 425KiB/s] [                   <=>    ]
Loaded image: uptimer:latest

Cunsigliu: Se avete bisognu di una mansa di parametri per cunnette à un servitore via SSH, pudete micca esse aduprà u schedariu ~/.ssh/config.

Trasferendu l'imaghjini via docker image save/load - Questu hè u metudu più minimalista, ma micca l'unicu. Ci sò altri:

  1. Registru di Container (standard di l'industria).
  2. Cunnettete à u servitore docker daemon da un altru host:
    1. variabile ambientale DOCKER_HOST.
    2. Opzione di linea di cummanda -H o --host strumentu docker-compose.
    3. docker context

U sicondu mètudu (cù trè opzioni per a so implementazione) hè ben descrittu in l'articulu Cumu implementà nantu à l'ospiti Docker remoti cù docker-compose.

deploy.sh

Avà cullemu tuttu ciò chì avemu fattu manualmente in un script. Accuminciamu cù a funzione di primu livellu, è dopu fighjate à l'altri utilizati in questu.

Tecniche interessanti

  • ${parameter?err_msg} - unu di l'incantesimi magichi bash (aka sustituzione di paràmetri). Se parameter micca specificatu, output err_msg è esce cù u codice 1.
  • docker --log-driver journald - per automaticamente, u driver di logging docker hè un schedariu di testu senza rotazione. Cù questu approcciu, i logs riempianu rapidamente u discu sanu, cusì per un ambiente di produzzione hè necessariu di cambià u driver per un più intelligente.

Script di implementazione

deploy() {
    local usage_msg="Usage: ${FUNCNAME[0]} image_name"
    local image_name=${1?$usage_msg}

    ensure-reverse-proxy || return 2
    if get-active-slot $image_name
    then
        local OLD=${image_name}_BLUE
        local new_slot=GREEN
    else
        local OLD=${image_name}_GREEN
        local new_slot=BLUE
    fi
    local NEW=${image_name}_${new_slot}
    echo "Deploying '$NEW' in place of '$OLD'..."
    docker run 
        --detach 
        --restart always 
        --log-driver journald 
        --name $NEW 
        --network web-gateway 
        $image_name || return 3
    echo "Container started. Checking health..."
    for i in {1..20}
    do
        sleep 1
        if get-service-status $image_name $new_slot
        then
            echo "New '$NEW' service seems OK. Switching heads..."
            sleep 2  # Ensure service is ready
            set-active-slot $image_name $new_slot || return 4
            echo "'$NEW' service is live!"
            sleep 2  # Ensure all requests were processed
            echo "Killing '$OLD'..."
            docker rm -f $OLD
            docker image prune -f
            echo "Deployment successful!"
            return 0
        fi
        echo "New '$NEW' service is not ready yet. Waiting ($i)..."
    done
    echo "New '$NEW' service did not raise, killing it. Failed to deploy T_T"
    docker rm -f $NEW
    return 5
}

Funzioni utilizati:

  • ensure-reverse-proxy - Assicura chì u proxy inversu funziona (utile per a prima implementazione)
  • get-active-slot service_name - Determina quale slot hè attualmente attivu per un serviziu determinatu (BLUE o GREEN)
  • get-service-status service_name deployment_slot - Determina se u serviziu hè prontu per processà e richieste entrate
  • set-active-slot service_name deployment_slot - Cambia a cunfigurazione nginx in u containeru proxy inversu

In ordine:

ensure-reverse-proxy() {
    is-container-up reverse-proxy && return 0
    echo "Deploying reverse-proxy..."
    docker network create web-gateway
    docker run 
        --detach 
        --restart always 
        --log-driver journald 
        --name reverse-proxy 
        --network web-gateway 
        --publish 80:80 
        nginx:alpine || return 1
    docker exec --interactive reverse-proxy sh -c "> /etc/nginx/conf.d/default.conf"
    docker exec reverse-proxy nginx -s reload
}

is-container-up() {
    local container=${1?"Usage: ${FUNCNAME[0]} container_name"}

    [ -n "$(docker ps -f name=${container} -q)" ]
    return $?
}

get-active-slot() {
    local service=${1?"Usage: ${FUNCNAME[0]} service_name"}

    if is-container-up ${service}_BLUE && is-container-up ${service}_GREEN; then
        echo "Collision detected! Stopping ${service}_GREEN..."
        docker rm -f ${service}_GREEN
        return 0  # BLUE
    fi
    if is-container-up ${service}_BLUE && ! is-container-up ${service}_GREEN; then
        return 0  # BLUE
    fi
    if ! is-container-up ${service}_BLUE; then
        return 1  # GREEN
    fi
}

get-service-status() {
    local usage_msg="Usage: ${FUNCNAME[0]} service_name deployment_slot"
    local service=${1?usage_msg}
    local slot=${2?$usage_msg}

    case $service in
        # Add specific healthcheck paths for your services here
        *) local health_check_port_path=":8080/" ;;
    esac
    local health_check_address="http://${service}_${slot}${health_check_port_path}"
    echo "Requesting '$health_check_address' within the 'web-gateway' docker network:"
    docker run --rm --network web-gateway alpine 
        wget --timeout=1 --quiet --server-response $health_check_address
    return $?
}

set-active-slot() {
    local usage_msg="Usage: ${FUNCNAME[0]} service_name deployment_slot"
    local service=${1?$usage_msg}
    local slot=${2?$usage_msg}
    [ "$slot" == BLUE ] || [ "$slot" == GREEN ] || return 1

    get-nginx-config $service $slot | docker exec --interactive reverse-proxy sh -c "cat > /etc/nginx/conf.d/$service.conf"
    docker exec reverse-proxy nginx -t || return 2
    docker exec reverse-proxy nginx -s reload
}

funziunava get-active-slot richiede un pocu di spiegazione:

Perchè torna un numeru è ùn pruduce micca una stringa?

In ogni casu, in a funzione di chjamà cuntrollemu u risultatu di u so travagliu, è cuntrollà u codice di uscita cù bash hè assai più faciule ch'è cuntrollà una stringa. Inoltre, ottene una stringa da questu hè assai simplice:
get-active-slot service && echo BLUE || echo GREEN.

Sò trè cundizioni veramente abbastanza per distingue tutti i stati?

Impiegazione Blue-Green à i salari minimi

Ancu dui seranu abbastanza, l'ultimu hè quì solu per cumplettà, per ùn scrive micca else.

Solu a funzione chì rende nginx configs resta indefinitu: get-nginx-config service_name deployment_slot. Per analogia cù u cuntrollu di salute, quì pudete stabilisce ogni cunfigurazione per ogni serviziu. Di e cose interessanti - solu cat <<- EOF, chì permette di sguassà tutte e tabulazioni à u principiu. True, u prezzu di un bonu furmatu hè mischju di tabulazioni cù spazii, chì oghje hè cunsideratu forma assai mala. Ma bash force tabulazioni, è saria ancu piacevule per avè un furmatu normale in a cunfigurazione nginx. In corta, mischjà tabulazioni cù spazii quì pare veramente a megliu suluzione da u peghju. Tuttavia, ùn vi vede micca questu in u snippet sottu, postu chì Habr "fa bè" cambiendu tutte e tabulazioni à spazii 4 è rende l'EOF invalidu. È quì si nota.

Per ùn esse alzatu duie volte, vi dicu subitu cat << 'EOF', chì serà scontru dopu. Se scrivite solu cat << EOF, allora in heredoc a stringa hè interpolata (e variabili sò allargate ($foo), chjama di cumanda ($(bar)) etc.), è se inserite a fine di u documentu in virgulette singuli, allora l'interpolazione hè disattivata è u simbulu $ hè visualizatu cum'è. Ciò chì avete bisognu di inserisce un script in un altru script.

get-nginx-config() {
    local usage_msg="Usage: ${FUNCNAME[0]} service_name deployment_slot"
    local service=${1?$usage_msg}
    local slot=${2?$usage_msg}
    [ "$slot" == BLUE ] || [ "$slot" == GREEN ] || return 1

    local container_name=${service}_${slot}
    case $service in
        # Add specific nginx configs for your services here
        *) nginx-config-simple-service $container_name:8080 ;;
    esac
}

nginx-config-simple-service() {
    local usage_msg="Usage: ${FUNCNAME[0]} proxy_pass"
    local proxy_pass=${1?$usage_msg}

cat << EOF
server {
    listen 80;
    location / {
        proxy_pass http://$proxy_pass;
    }
}
EOF
}

Questu hè u script tutale. È cusì Gist cù questu script per scaricà via wget o curl.

Esecuzione di scripts parametrizzati nantu à un servitore remoto

Hè ora di chjappà in u servitore di destinazione. Sta volta localhost abbastanza adattatu:

$ ssh-copy-id localhost
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
himura@localhost's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'localhost'"
and check to make sure that only the key(s) you wanted were added.

Avemu scrittu un script di implementazione chì scarica una maghjina pre-custruita à u servitore di destinazione è rimpiazza perfettamente u containeru di serviziu, ma cumu pudemu eseguisce in una macchina remota? U script hà argumenti, postu chì hè universale è pò implementà parechji servizii à una volta sottu un proxy inversu (pudete aduprà nginx configs per determinà quale url serà quale serviziu). U script ùn pò micca esse guardatu in u servitore, postu chì in questu casu ùn pudemu micca aghjurnà automaticamente (per u scopu di correzioni di bug è aghjunghje novi servizii), è in generale, state = male.

Soluzione 1: Almacenà sempre u script in u servitore, ma copiate ogni volta scp. Allora cunnette via ssh è eseguisce u script cù l'argumenti necessarii.

Cons:

  • Dui azzioni invece di una
  • Ùn ci hè micca un locu induve copià, o ùn ci pò micca esse accessu à questu, o u script pò esse eseguitu à u mumentu di a sustituzione.
  • Hè cunsigliatu di pulizziari dopu à sè stessu (sguassate u script).
  • Dighjà trè azzioni.

Soluzione 2:

  • Mantene solu definizione di funzioni in u script è ùn eseguite nunda
  • Cù l'aiutu di sed aghjunghje una funzione chjamata à a fine
  • Mandate tuttu direttamente à shh via pipe (|)

Pros:

  • Veramente senza statu
  • Nisuna entità boilerplate
  • Sentu cool

Facemu solu senza Ansible. Iè, tuttu hè digià inventatu. Iè, una bicicletta. Fighjate quantu hè simplice, elegante è minimalista a bicicletta:

$ cat << 'EOF' > deploy.sh
#!/bin/bash

usage_msg="Usage: $0 ssh_address local_image_tag"
ssh_address=${1?$usage_msg}
image_name=${2?$usage_msg}

echo "Connecting to '$ssh_address' via ssh to seamlessly deploy '$image_name'..."
( sed "$a deploy $image_name" | ssh -T $ssh_address ) << 'END_OF_SCRIPT'
deploy() {
    echo "Yay! The '${FUNCNAME[0]}' function is executing on '$(hostname)' with argument '$1'"
}
END_OF_SCRIPT
EOF

$ chmod +x deploy.sh

$ ./deploy.sh localhost magic-porridge-pot
Connecting to localhost...
Yay! The 'deploy' function is executing on 'hut' with argument 'magic-porridge-pot'

Tuttavia, ùn pudemu micca esse sicuru chì l'ospite remotu hà bash adattatu, cusì aghjunghjemu un picculu cuntrollu à u principiu (questu hè invece di shellbang):

if [ "$SHELL" != "/bin/bash" ]
then
    echo "The '$SHELL' shell is not supported by 'deploy.sh'. Set a '/bin/bash' shell for '$USER@$HOSTNAME'."
    exit 1
fi

È avà hè vera:

$ docker exec reverse-proxy rm /etc/nginx/conf.d/default.conf

$ wget -qO deploy.sh https://git.io/JUURc

$ chmod +x deploy.sh

$ ./deploy.sh localhost uptimer
Sending gzipped image 'uptimer' to 'localhost' via ssh...
Loaded image: uptimer:latest
Connecting to 'localhost' via ssh to seamlessly deploy 'uptimer'...
Deploying 'uptimer_GREEN' in place of 'uptimer_BLUE'...
06f5bc70e9c4f930e7b1f826ae2ca2f536023cc01e82c2b97b2c84d68048b18a
Container started. Checking health...
Requesting 'http://uptimer_GREEN:8080/' within the 'web-gateway' docker network:
  HTTP/1.0 503 Service Unavailable
wget: server returned error: HTTP/1.0 503 Service Unavailable
New 'uptimer_GREEN' service is not ready yet. Waiting (1)...
Requesting 'http://uptimer_GREEN:8080/' within the 'web-gateway' docker network:
  HTTP/1.0 503 Service Unavailable
wget: server returned error: HTTP/1.0 503 Service Unavailable
New 'uptimer_GREEN' service is not ready yet. Waiting (2)...
Requesting 'http://uptimer_GREEN:8080/' within the 'web-gateway' docker network:
  HTTP/1.0 200 OK
  Server: BaseHTTP/0.6 Python/3.8.3
  Date: Sat, 22 Aug 2020 20:15:50 GMT
  Content-Type: text/html

New 'uptimer_GREEN' service seems OK. Switching heads...
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
2020/08/22 20:15:54 [notice] 97#97: signal process started
The 'uptimer_GREEN' service is live!
Killing 'uptimer_BLUE'...
uptimer_BLUE
Total reclaimed space: 0B
Deployment successful!

Avà pudete apre http://localhost/ in u navigatore, eseguite l'implementazione di novu è assicuratevi chì funziona perfettamente aghjurnendu a pagina secondu u CD durante u layout.

Ùn vi scurdate di pulizziari dopu à u travagliu :3

$ docker rm -f uptimer_GREEN reverse-proxy 
uptimer_GREEN
reverse-proxy

$ docker network rm web-gateway 
web-gateway

$ cd ..

$ rm -r blue-green-deployment

Source: www.habr.com