Blue-Green Deployment ka bonyane ba meputso

Sehloohong sena re sebelisa Bash, ssh, docker и nginx Re tla hlophisa moralo o se nang moeli oa sesebelisoa sa marang-rang. Ho tsamaisoa ha botala bo botala ke mokhoa o u lumellang hore u ntlafatse ts'ebeliso hang hang ntle le ho hana kopo e le 'ngoe. Ke e 'ngoe ea maano a ho beha nako ea ho theola nako 'me e loketse lits'ebetso tse nang le mohlala o le mong, empa bokhoni ba ho kenya mohlala oa bobeli, o ikemiselitseng ho sebetsa haufi.

Ha re re u na le ts'ebeliso ea webo eo bareki ba bangata ba sebetsang ka eona, 'me ha ho na mokhoa oa hore e ka robala metsotsoana e seng mekae. 'Me u hlile u hloka ho hlahisa ntlafatso ea laeborari, tokiso ea liphoso, kapa karolo e ncha e pholileng. Boemong bo tloaelehileng, o tla hloka ho emisa ts'ebeliso, o e nkele sebaka ebe o qala hape. Tabeng ea docker, u ka qala ho e nkela sebaka, ebe u e qala hape, empa ho ntse ho tla ba le nako eo ka eona likopo tsa kopo li ke keng tsa sebetsoa, ​​​​hobane hangata kopo e nka nako ho qala. Ho thoe'ng haeba e qala, empa e bonahala e sa sebetse? Ena ke bothata, a re e rarolleng ka mekhoa e fokolang le ka bokhabane kamoo ho ka khonehang.

TLHOKOMELISO: Boholo ba sengoloa se hlahisoa ka mokhoa oa liteko - ka mokhoa oa ho rekota seshene ea khomphutha. Re tšepa hore sena ha se na ho ba thata haholo ho utloisisa 'me khoutu e tla ingolisa ka ho lekaneng. Bakeng sa sepakapaka, nahana hore tsena ha se likhechana tsa khoutu feela, empa pampiri e tsoang ho mofuta oa mohala oa "tšepe".

Blue-Green Deployment ka bonyane ba meputso

Mekhoa e khahlisang eo ho leng thata ho Google ka ho bala khoutu e hlalositsoe qalong ea karolo ka 'ngoe. Haeba ho na le ntho e 'ngoe e sa hlakeheng, e google 'me u e hlahlobe. explainshell (ka lehlohonolo, e sebetsa hape, ka lebaka la ho buloa ha thelekramo). Haeba u sa tsebe letho ka Google, botsa maikutlong. Ke tla thabela ho eketsa karolo e lumellanang "Mekhoa e thahasellisang".

Ha re qaleng.

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

tšebeletso ea

Ha re etseng tšebeletso ea liteko 'me re e behe ka har'a setshelo.

Mekhoa e khahlisang

  • cat << EOF > file-name (Mona Tokomane + I/O Redirection) ke mokhoa oa ho etsa faele ea mela e mengata ka taelo e le 'ngoe. Ntho e ngoe le e ngoe bash e bala ho tsoa /dev/stdin kamora mola ona le pele ho mola EOF e tla rekotwa ho file-name.
  • wget -qO- URL (explainshell) - hlahisa tokomane e amohetsoeng ka HTTP ho /dev/stdout (analogue curl URL).

Hatisa

Ke roba snippet ka ho khetheha ho thusa ho totobatsa Python. Qetellong ho tla ba le sengoathoana se seng se kang sena. Ak'u nahane hore libakeng tsena pampiri e ne e khaotsoe hore e romeloe lefapheng la ho totobatsa (moo khoutu e neng e ngotsoe ka letsoho ka li-highlighters), ebe likotoana tsena li kenngoa morao.

$ 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

Moemeli oa morao

E le hore kopo ea rona e khone ho fetoha e sa hlokomeloe, ho hlokahala hore ho be le mokhatlo o mong ka pel'a eona o tla pata sebaka sa eona. E ka 'na ea e-ba setsi sa marang-rang nginx в moemeli oa morao-rao. Ho thehiloe proxy e ka morao pakeng tsa moreki le kopo. E amohela likopo ho tsoa ho bareki mme e li fetisetsa ho kopo ebe e fetisetsa likarabo tsa kopo ho bareki.

Sesebelisoa le proxy e ka morao e ka hokahanngoa ka hare ho docker e sebelisa marang-rang a docker. Ka hona, sets'oants'o se nang le ts'ebeliso ha se hloke le ho fetisetsa kou ho sistimi ea moamoheli; sena se lumella ts'ebeliso hore e qheleloe ka thoko ho litšokelo tsa kantle.

Haeba moemeli ea ka morao a lula ho moamoheli e mong, o tla tlameha ho lahla marang-rang a li-docker ebe o hokela sesebelisoa ho proxy e ka morao ka marang-rang a moamoheli, o fetisetsa koung. ditiriso paramethara --publish, joalo ka qalong le joalo ka proxy e ka morao.

Re tla tsamaisa proxy e ka morao ho port 80, hobane sena ke sona hantle se lokelang ho mamela marang-rang a kantle. Haeba port 80 e phathahane ho moamoheli oa hau oa liteko, fetola paramente --publish 80:80 mabapi le --publish ANY_FREE_PORT:80.

Mekhoa e khahlisang

Hatisa

$ 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>

Tšebeliso e se nang moeli

Ha re hlahise mofuta o mocha oa ts'ebeliso (ka matlafatso ea ts'ebetso ea ho qala habeli) 'me re leke ho e sebelisa ntle le moroallo.

Mekhoa e khahlisang

  • echo 'my text' | docker exec -i my-container sh -c 'cat > /my-file.txt' — Ngola mongolo my text ho file /my-file.txt ka hare ho setshelo my-container.
  • cat > /my-file.txt — Ngola dikahare tsa mongolo o tlwaelehileng faeleng /dev/stdin.

Hatisa

$ 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

Nakong ena, setšoantšo se hahiloe ka ho toba ho seva, se hlokang hore mehloli ea lisebelisoa e be teng, hape e jarisa seva ka mosebetsi o sa hlokahaleng. Mohato o latelang ke ho abela kopano ea setšoantšo mochine o arohaneng (mohlala, ho tsamaiso ea CI) ebe o e fetisetsa ho seva.

Ho fetisa litšoantšo

Ka bomalimabe, ha ho utloahale ho fetisetsa litšoantšo ho tloha sebakeng sa lehae ho ea sebakeng sa lehae, kahoo karolo ena e ka hlahlojoa feela haeba u na le batho ba babeli ba nang le Docker e haufi. Bonyane e shebahala tjena:

$ 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

sehlopha docker save e boloka boitsebiso ba setšoantšo polokelong ea .tar, ho bolelang hore boima ba eona bo ka makgetlo a 1.5 ho feta kamoo bo neng bo ka lekanya kateng ka foromo e petelitsoeng. Kahoo ha re e sisinye ka lebitso la ho boloka nako le sephethephethe:

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

U ka shebella ts'ebetso ea ho jarolla (leha sena se hloka ts'ebeliso ea motho oa boraro):

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

Keletso: Haeba u hloka sehlopha sa liparamente ho hokela seva ka SSH, mohlomong ha u sebelise faele. ~/.ssh/config.

Ho fetisa setšoantšo ka docker image save/load - Ena ke mokhoa o fokolang ka ho fetisisa, empa ha se oona feela. Ho na le tse ling:

  1. Registry ea Container (tekanyetso ea indasteri).
  2. Hokela ho seva ea daemon ea docker ho tsoa ho moamoheli e mong:
    1. tikoloho e fapaneng DOCKER_HOST.
    2. Khetho ea mola oa taelo -H kapa --host seletsa docker-compose.
    3. docker context

Mokhoa oa bobeli (o nang le likhetho tse tharo bakeng sa ts'ebetsong ea oona) o hlalositsoe hantle sehloohong sena Mokhoa oa ho kenya li-host tsa Docker tse hole ka docker-compose.

deploy.sh

Joale a re bokelleng tsohle tseo re li entseng ka letsoho ho sengoloa se le seng. Ha re qaleng ka tšebetso ea boemo bo holimo, ebe re sheba tse ling tse sebelisitsoeng ho eona.

Mekhoa e khahlisang

  • ${parameter?err_msg} - e 'ngoe ea boloi ba bash (aka sebaka sa parameter). Haeba parameter e sa hlalosoang, tlhahiso err_msg ebe o tsoa ka khoutu 1.
  • docker --log-driver journald - ka mokhoa o ikhethileng, mokhanni oa ho rema lifate ke faele ea mongolo ntle le ho potoloha. Ka mokhoa ona, li-log li potlakela ho tlatsa disk eohle, kahoo bakeng sa tikoloho ea tlhahiso ho hlokahala ho fetola mokhanni ho ea bohlale.

Sengoloa sa ho tsamaisa

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
}

Lintlha tse sebelisitsoeng:

  • ensure-reverse-proxy - E etsa bonnete ba hore proxy e ka morao ea sebetsa (e molemo bakeng sa thomello ea pele)
  • get-active-slot service_name - E khetha hore na ke slot efe e sebetsang hajoale bakeng sa ts'ebeletso e fanoeng (BLUE kapa GREEN)
  • get-service-status service_name deployment_slot - E etsa qeto ea hore na tšebeletso e se e loketse ho sebetsana le likopo tse tlang
  • set-active-slot service_name deployment_slot - E fetola tlhophiso ea nginx ka har'a setshelo sa proxy se ka morao

Ka tatellano:

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
}

Mosebetsi get-active-slot e hloka tlhaloso e nyane:

Hobaneng e khutlisa nomoro mme e sa hlahise khoele?

Leha ho le joalo, ts'ebetsong ea ho letsetsa re hlahloba sephetho sa mosebetsi oa eona, 'me ho hlahloba khoutu ea ho tsoa ho sebelisa bash ho bonolo haholo ho feta ho hlahloba khoele. Ho feta moo, ho fumana khoele ho eona ho bonolo haholo:
get-active-slot service && echo BLUE || echo GREEN.

Na maemo a mararo a lekane ho khetholla linaha tsohle?

Blue-Green Deployment ka bonyane ba meputso

Esita le tse peli li tla lekana, tsa ho qetela li teng mona bakeng sa botlalo feela, e le hore u se ke ua ngola else.

Ke ts'ebetso feela e khutlisetsang nginx configs e lulang e sa hlalosoa: get-nginx-config service_name deployment_slot. Ka papiso le tlhahlobo ea bophelo bo botle, mona o ka beha tlhophiso efe kapa efe bakeng sa ts'ebeletso efe kapa efe. Har'a lintho tse thahasellisang - feela cat <<- EOF, e u lumellang hore u tlose li-tab tsohle qalong. Ke 'nete, theko ea ho fomata hantle ke li-tab tse tsoakiloeng le libaka, tseo kajeno li nkoang e le mofuta o mobe haholo. Empa li-tab tsa matla a bash, hape ho ka ba monate ho ba le fomate e tloaelehileng ho nginx config. Ka bokhutšoanyane, ho kopanya li-tab le libaka mona ho hlile ho bonahala e le tharollo e molemo ka ho fetisisa ho tse mpe ka ho fetisisa. Leha ho le joalo, u ke ke ua bona sena ho snippet e ka tlase, kaha Habr "o e etsa hantle" ka ho fetola li-tab tsohle ho libaka tsa 4 le ho etsa hore EOF e se ke ea sebetsa. Mme mona hoa hlokomeleha.

E le hore u se ke ua tsoha habeli, ke tla u bolella hang-hang ka cat << 'EOF', tse tla kopana hamorao. Haeba u ngola habonolo feela cat << EOF, ebe ka hare ho heredoc khoele e kenngoa (li-variables li atolosoa ($foo), mehala ea taelo ($(bar)), joalo-joalo), 'me haeba u kenyelletsa pheletso ea tokomane ka mantsoe a qotsitsoeng a le mong, poleloana e ea tima 'me letšoao $ e bonts'oa joalo ka. Seo u se hlokang ho kenya script ka har'a script e 'ngoe.

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
}

Ena ke script kaofela. Me, ea ba hlaka ka script ena bakeng sa ho khoasolla ka wget kapa curl.

E etsa lingoloa tse nang le parameter ho seva e hole

Ke nako ea ho kokota ho server targeted. Lekhetlong lena localhost e loketse hantle:

$ 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.

Re ngotse sengoloa sa deployment se khoasollang sets'oants'o se hahiloeng esale pele ho seva se shebiloeng ebe se nka sebaka sa sets'oants'o sa lits'ebeletso ka mokhoa o sa reroang, empa re ka se etsa joang mochining o hole? Sengoloa se na le likhang, kaha se na le lefats'e mme se ka tsamaisa lits'ebeletso tse 'maloa ka nako e le ngoe tlasa proxy e le 'ngoe (o ka sebelisa nginx configs ho fumana hore na url e tla ba tšebeletso efe). Script e ke ke ea bolokoa ho seva, kaha tabeng ena re ke ke ra khona ho e ntlafatsa ka bo eona (ka morero oa ho lokisa liphoso le ho eketsa litšebeletso tse ncha), 'me ka kakaretso, boemo = bobe.

Tharollo 1: E ntse e boloka script ho seva, empa e kopitse nako le nako scp. Ebe u hokahanya ka ssh le ho phethahatsa sengoloa ka mabaka a hlokahalang.

Chelete:

  • Liketso tse peli ho e-na le e le 'ngoe
  • Ho ka 'na ha se ke ha e-ba le sebaka seo u kopitsang ho sona, kapa ho ka 'na ha se ke ha e-ba le monyetla oa ho se fumana, kapa script e ka etsoa ka nako ea ho fetola.
  • Ho eletsoa hore u itlhoekise ka mor'a hao (hlakola script).
  • E se e le ketso tse tharo.

Tharollo 2:

  • Boloka feela litlhaloso tsa tšebetso ka har'a script 'me u se ke ua sebelisa letho ho hang
  • Ka thuso ea sed kenya tshebetsong call qetellong
  • E romelle kaofela ka kotloloho ho shh ka pipe (|)

Melemo:

  • Ruri ha ho naha
  • Ha ho mekhatlo ea li-boilerplate
  • Ho ikutloa hamonate

Ha re e etse ntle le Ansible. E, ntho e 'ngoe le e' ngoe e se e qapiloe. E, baesekele. Sheba hore na baesekele e bonolo hakae, e boreleli ebile e le minimalistic:

$ 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'

Leha ho le joalo, ha re na bonnete ba hore moamoheli ea hole o na le bash e lekaneng, kahoo re tla eketsa cheke e nyane qalong (sena ke sebakeng sa 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

'Me joale ke 'nete:

$ 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!

Joale u ka bula http://localhost/ ho sebatli, tsamaisa thomello hape 'me u netefatse hore e sebetsa ka mokhoa o sa reroang ka ho nchafatsa leqephe ho latela CD nakong ea moralo.

U se ke ua lebala ho hloekisa ka mor'a mosebetsi :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