Kuv tshwj xeeb rhuav tshem cov kab lus kom ua kom pom tseeb rau Python. Thaum kawg yuav muaj lwm daim zoo li no. Xav txog tias nyob rau hauv cov chaw no daim ntawv raug txiav xa mus rau lub chaw ua haujlwm tseem ceeb (qhov twg cov cai yog xim tes xim nrog cov highlighters), thiab tom qab ntawd cov ntawv no tau muab rov qab.
$ 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
Rov qab tso npe
Txhawm rau kom peb daim ntawv thov tuaj yeem hloov pauv tsis pom, nws yog qhov tsim nyog uas yuav tsum muaj qee qhov chaw ua ntej ntawm nws uas yuav zais nws qhov hloov pauv. Nws tuaj yeem yog lub vev xaib server nginx Π² rov qab proxy hom. Lub npe rov qab yog tsim los ntawm tus neeg siv khoom thiab daim ntawv thov. Nws lees txais kev thov los ntawm cov neeg siv khoom thiab xa lawv mus rau daim ntawv thov thiab xa daim ntawv thov cov lus teb rau cov neeg siv khoom.
Daim ntawv thov thiab thim rov qab tuaj yeem txuas rau hauv docker siv docker network. Yog li, lub thawv nrog daim ntawv thov tsis tas yuav xa mus rau qhov chaw nres nkoj ntawm tus tswv system; qhov no tso cai rau daim ntawv thov raug cais tawm ntau tshaj plaws los ntawm kev hem sab nraud.
Yog tias tus neeg sawv cev rov qab nyob ntawm lwm tus tswv tsev, koj yuav tsum tso tseg lub docker network thiab txuas daim ntawv thov mus rau lub npe rov qab los ntawm tus tswv network, xa mus rau qhov chaw nres nkoj. apps parameter --publish, raws li thaum pib thawj zaug thiab ib yam li nrog lub npe rov qab.
Peb yuav khiav lub npe rov qab ntawm qhov chaw nres nkoj 80, vim tias qhov no yog qhov chaw uas yuav tsum tau mloog rau sab nraud network. Yog tias qhov chaw nres nkoj 80 tsis khoom rau koj tus tswv tsev xeem, hloov qhov ntsuas --publish 80:80 rau --publish ANY_FREE_PORT:80.
$ 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
Nyob rau theem no, cov duab tau tsim ncaj qha rau ntawm tus neeg rau zaub mov, uas yuav tsum muaj cov ntaub ntawv thov kom nyob ntawd, thiab tseem thauj cov neeg rau zaub mov nrog kev ua haujlwm tsis tsim nyog. Cov kauj ruam tom ntej yog faib cov duab sib dhos rau lub tshuab cais (piv txwv li, mus rau CI system) thiab tom qab ntawd hloov mus rau lub server.
Hloov cov duab
Hmoov tsis zoo, nws tsis muaj txiaj ntsig los hloov cov duab los ntawm localhost mus rau localhost, yog li ntu no tsuas tuaj yeem tshawb xyuas yog tias koj muaj ob tus tswv nrog Docker ntawm tes. Yam tsawg kawg nws zoo li no:
$ 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
pab neeg docker save txuag cov duab cov ntaub ntawv hauv .tar archive, txhais tau tias nws hnyav li 1.5 npaug ntau dua li nws yuav hnyav hauv daim ntawv compressed. Yog li cia peb co nws nyob rau hauv lub npe ntawm txuag lub sij hawm thiab tsheb khiav:
Tam sim no cia peb sau txhua yam peb tau ua manually rau hauv ib tsab ntawv. Cia peb pib nrog cov haujlwm saum toj kawg nkaus, thiab tom qab ntawd saib lwm tus siv hauv nws.
docker --log-driver journald - los ntawm lub neej ntawd, tus tsav tsheb nkag docker yog cov ntawv nyeem tsis muaj kev sib hloov. Nrog rau txoj hauv kev no, cov cav ceev nrawm sau tag nrho cov disk, yog li rau qhov chaw tsim khoom nws yog qhov tsim nyog los hloov tus tsav tsheb mus rau qhov ntse dua.
Deployment script
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
}
Feature siv:
ensure-reverse-proxy - Xyuas kom tseeb tias lub npe rov qab ua haujlwm (pab tau rau thawj zaug xa tawm)
get-active-slot service_name - Txiav txim siab seb qhov twg yog tam sim no ua haujlwm rau ib qho kev pabcuam (BLUE los yog GREEN)
get-service-status service_name deployment_slot - Txiav txim siab seb qhov kev pabcuam puas npaj txhij los ua cov ntawv thov tuaj
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
}
muaj nuj nqi get-active-slot yuav tsum tau piav me ntsis:
Vim li cas nws rov qab tus lej thiab tsis tso tawm ib txoj hlua?
Xijpeem, hauv kev hu xov tooj ua haujlwm peb xyuas qhov tshwm sim ntawm nws txoj haujlwm, thiab tshawb xyuas cov lej tawm siv bash yog qhov yooj yim dua li kev txheeb xyuas txoj hlua. Tsis tas li ntawd, tau txais ib txoj hlua los ntawm nws yog qhov yooj yim heev: get-active-slot service && echo BLUE || echo GREEN.
Peb cov xwm txheej puas txaus los paub qhov txawv ntawm txhua lub xeev?
Txawm tias ob yuav txaus, qhov kawg nyob ntawm no tsuas yog ua kom tiav, thiaj li tsis sau else.
Tsuas yog cov haujlwm uas rov qab nginx configs tseem tsis tau txhais: get-nginx-config service_name deployment_slot. Los ntawm kev sib piv nrog kev kuaj mob, ntawm no koj tuaj yeem teeb tsa ib qho kev teeb tsa rau ib qho kev pabcuam. Ntawm cov khoom nthuav - nkaus xwb cat <<- EOF, uas tso cai rau koj tshem tawm tag nrho cov tabs thaum pib. Muaj tseeb tiag, tus nqi ntawm qhov zoo formatting yog sib xyaw tabs nrog qhov chaw, uas niaj hnub no suav hais tias yog daim ntawv phem heev. Tab sis bash quab yuam tabs, thiab nws kuj yuav zoo kom muaj kev ua kom zoo li qub hauv nginx config. Hauv luv luv, sib xyaw tab nrog qhov chaw ntawm no tiag tiag zoo li qhov kev daws teeb meem zoo tshaj plaws ntawm qhov phem tshaj plaws. Txawm li cas los xij, koj yuav tsis pom qhov no hauv cov kab lus hauv qab no, txij li Habr "ua nws zoo" los ntawm kev hloov tag nrho cov tab rau 4 qhov chaw thiab ua rau EOF tsis raug. Thiab ntawm no nws yog pom.
Yog li tsis txhob sawv ob zaug, kuv mam li qhia koj tam sim ntawd txog cat << 'EOF', uas yuav ntsib tom qab. Yog koj sau yooj yim cat << EOF, ces nyob rau hauv heredoc txoj hlua yog interpolated (kuj txawv txawv yog nthuav ($foo), command calls ($(bar)) thiab lwm yam), thiab yog tias koj kaw qhov kawg ntawm cov ntaub ntawv nyob rau hauv ib nqe lus, ces interpolation yog neeg xiam thiab lub cim $ yog tso tawm raws li yog. Dab tsi koj yuav tsum tau ntxig ib tsab ntawv hauv lwm tsab ntawv.
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
}
Nov yog tag nrho tsab ntawv. Thiab yog li ntawd gist nrog tsab ntawv no rau rub tawm ntawm wget lossis curl.
Ua haujlwm parameterized scripts ntawm lub chaw taws teeb server
Nws yog lub sijhawm los khob ntawm lub hom phiaj server. Lub sijhawm no localhost haum heev:
$ 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.
Peb tau sau ib tsab ntawv xa mus uas rub tawm cov duab ua ntej rau lub hom phiaj server thiab hloov pauv lub thawv pabcuam, tab sis peb yuav ua li cas rau ntawm lub tshuab chaw taws teeb? Tsab ntawv muaj cov lus sib cav, vim nws yog universal thiab tuaj yeem siv ntau qhov kev pabcuam ib zaug hauv ib lub npe rov qab (koj tuaj yeem siv nginx configs los txiav txim seb qhov url yuav yog qhov kev pabcuam twg). Cov ntawv sau tsis tuaj yeem khaws cia rau ntawm lub server, txij li qhov no peb yuav tsis tuaj yeem hloov kho nws tau txais (rau lub hom phiaj ntawm kev kho kab laum thiab ntxiv cov kev pabcuam tshiab), thiab feem ntau, xeev = kev phem.
Kev daws 1: Tseem khaws cov ntawv sau rau ntawm lub server, tab sis luam nws txhua lub sijhawm scp. Ces txuas ntawm ssh thiab ua tiav tsab ntawv nrog cov lus sib cav tsim nyog.
Txais:
Ob yam ua tsis yog ib qho
Tej zaum yuav tsis muaj qhov chaw uas koj luam tawm, lossis tsis tuaj yeem nkag mus rau nws, lossis cov ntawv yuav raug tua thaum lub sijhawm hloov pauv.
Nws raug nquahu kom ntxuav tom qab koj tus kheej (rho tawm tsab ntawv).
Twb tau peb ua.
Kev daws 2:
Khaws cov ntsiab lus ua haujlwm nkaus xwb hauv tsab ntawv thiab khiav tsis muaj dab tsi hlo li
Nrog kev pab los ntawm sed ntxiv kev hu xov tooj mus rau qhov kawg
Xa nws tag nrho ncaj qha rau shh ntawm cov yeeb nkab (|)
Tshaj:
Tseeb tiag tiag
Tsis muaj boilerplate qhov chaw
Xav txias
Cia peb ua nws yam tsis muaj Ansible. Yog, txhua yam twb tau invented. Yog, lub tsheb kauj vab. Saib yuav ua li cas yooj yim, elegant thiab minimalistic lub tsheb kauj vab yog:
$ 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'
Txawm li cas los xij, peb tsis tuaj yeem paub tseeb tias tus tswv tsev nyob deb muaj qhov txaus bash, yog li peb yuav ntxiv ib daim tshev me me thaum pib (qhov no tsis yog 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
Thiab tam sim no nws yog tiag:
$ 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!
Tam sim no koj tuaj yeem qhib http://localhost/ hauv qhov browser, khiav qhov kev xa tawm dua thiab xyuas kom meej tias nws khiav seamlessly los ntawm kev hloov kho nplooj ntawv raws li CD thaum lub sijhawm teeb tsa.
Tsis txhob hnov ββββqab ntxuav tom qab ua haujlwm: 3