Ko te tono wharangi-kotahi (SPA) he huinga o nga konae JavaScript me HTML, me nga whakaahua me etahi atu rauemi. Na te mea karekau ratou e huri tere, he tino ngawari te whakaputa i runga ipurangi. He maha nga ratonga utu iti me te kore utu mo tenei, timata mai i nga wharangi GitHub ngawari (me etahi me narod.ru) ka mutu ki te CDN penei i a Amazon S3. Heoi, i hiahia ahau ki tetahi atu mea.
I hiahia ahau ki tetahi ahua Docker me te SPA kia ngawari te whakarewahia i roto i te hanga hei waahanga o te roopu Kubernetes, me te miihini o te kaiwhakawhanake-muri kaore e mohio he aha te SPA.
Kua whakatauhia e au nga whakaritenga whakaahua e whai ake nei mo au ake:
- ngawari ki te whakamahi (engari ehara i te huihuinga);
- te rahi iti e rua mo te kōpae me te RAM;
- whirihoranga na roto i nga taurangi taiao kia taea ai te whakamahi i te ahua ki nga taiao rereke;
- te tohatoha tino pai o nga konae.
I tenei ra ka korero ahau ki a koe me pehea:
- nginx gut;
- hanga brotli mai i nga puna;
- whakaako i nga konae pateko kia mohio ki nga taurangi taiao;
- me pehea te kohikohi i tetahi ahua Docker mai i enei mea katoa.
Ko te kaupapa o tenei tuhinga he whakapuaki i aku wheako me te whakapataritari i nga mema mohio o te hapori ki te whakahee.
Te hanga pikitia mo te huihuinga
Kia iti te rahi o te ahua Docker whakamutunga, me piri koe ki nga ture e rua: he iti rawa nga paparanga me te ahua iti. Ko tetahi o nga whakaahua iti rawa ko te ahua Alpine Linux, na ko taku e whiriwhiri ai. Ko etahi ka tohe ko te Alpine kaore e pai mo te hanga, a he tika pea. Engari ko ahau ake, kare ano au i raru ki a ia, kaore hoki he tautohetohe ki a ia.
Kia iti ake nga paparanga, ka kohia e ahau te ahua ki nga waahanga e 2. Ko te tuatahi he tauira; ko nga taputapu awhina katoa me nga konae rangitahi ka noho ki roto. A i te wahanga whakamutunga ka tuhia e au te putanga whakamutunga o te tono.
Me timata ki te ahua awhina.
Hei whakahiato tono SPA, me hiahia koe ki te node.js. Ka tangohia e ahau te ahua mana, ka tae mai me nga kaiwhakahaere putea npm me te miro. Mo ahau ake, ka taapirihia e ahau te node-gyp, e hiahiatia ana hei hanga i etahi kohinga npm, me te Brotli compressor mai i a Google, ka whai hua ki a maatau i muri mai.
Dockerfile me nga korero.
# Базовый образ
FROM node:12-alpine
LABEL maintainer="Aleksey Maydokin <[email protected]>"
ENV BROTLI_VERSION 1.0.7
# Пакеты, которые нужны, чтобы собрать из исходников Brotli
RUN apk add --no-cache --virtual .build-deps
bash
gcc
libc-dev
make
linux-headers
cmake
curl
&& mkdir -p /usr/src
# Исходники Brotli скачиваем из официального репозитория
&& curl -LSs https://github.com/google/brotli/archive/v$BROTLI_VERSION.tar.gz | tar xzf - -C /usr/src
&& cd /usr/src/brotli-$BROTLI_VERSION
# Компилируем Brotli
&& ./configure-cmake --disable-debug && make -j$(getconf _NPROCESSORS_ONLN) && make install
# Добавляем node-gyp
&& yarn global add node-gyp
# Убираем за собой мусор
&& apk del .build-deps && yarn cache clean && rm -rf /usr/src
Kei konei ahau e whawhai ana mo te iti, no reira ka whakakotahihia te ahua e tetahi roopu nui.
Ka kitea te ahua kua oti i konei:
nginx
Ka taea e koe te whakamahi i tetahi tūmau tukutuku ki te tohatoha ihirangi pateko. Kua waia ahau ki te mahi me te nginx, no reira ka whakamahia e au inaianei.
Kei a Nginx tetahi ahua Docker mana, engari he maha rawa nga waahanga mo te tohatoha noa. Ko nga mea kei roto i te tuku ka kitea e tetahi roopu motuhake, i te Dockerfile mana ranei.
$ docker run --rm nginx:1-alpine nginx -V
nginx version: nginx/1.17.9
built by gcc 8.3.0 (Alpine 8.3.0)
built with OpenSSL 1.1.1d 10 Sep 2019
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --with-perl_modules_path=/usr/lib/perl5/vendor_perl --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-Os -fomit-frame-pointer' --with-ld-opt=-Wl,--as-needed
Ka whakamahia e ahau te Dockerfile hei turanga, engari ka waiho e au ko nga mea e hiahiatia ana hei tohatoha i nga ihirangi pateko. Kaore e taea e taku putanga te mahi i runga i te HTTPS, e kore e tautoko i te whakamanatanga, me te maha atu. Engari ka taea e taku putanga te tohatoha i nga konae kua kopirihia me te Brotli algorithm, he pai ake i te gzip. Ka kopirihia e matou nga konae kotahi; kaore he take ki te mahi i runga i te rere.
Koinei te Dockerfile i mutu i ahau. Ko nga korero i roto i te reo Rusia naku, i te reo Ingarihi - mai i te taketake.
Dockerfile
# Базовый образ снова Alpine
FROM alpine:3.9
LABEL maintainer="Aleksey Maydokin <[email protected]>"
ENV NGINX_VERSION 1.16.0
ENV NGX_BROTLI_VERSION 0.1.2
ENV BROTLI_VERSION 1.0.7
RUN set -x
&& addgroup -S nginx
&& adduser -D -S -h /var/cache/nginx -s /sbin/nologin -G nginx nginx
# Устанавливаем пакеты, которые нужны чтобы собрать nginx и модуль ngx_brotli к нему
&& apk add --no-cache --virtual .build-deps
gcc
libc-dev
make
linux-headers
curl
&& mkdir -p /usr/src
# Скачиваем исходники
&& curl -LSs https://nginx.org/download/nginx-$NGINX_VERSION.tar.gz | tar xzf - -C /usr/src
&& curl -LSs https://github.com/eustas/ngx_brotli/archive/v$NGX_BROTLI_VERSION.tar.gz | tar xzf - -C /usr/src
&& curl -LSs https://github.com/google/brotli/archive/v$BROTLI_VERSION.tar.gz | tar xzf - -C /usr/src
&& rm -rf /usr/src/ngx_brotli-$NGX_BROTLI_VERSION/deps/brotli/
&& ln -s /usr/src/brotli-$BROTLI_VERSION /usr/src/ngx_brotli-$NGX_BROTLI_VERSION/deps/brotli
&& cd /usr/src/nginx-$NGINX_VERSION
&& CNF="
--prefix=/etc/nginx
--sbin-path=/usr/sbin/nginx
--modules-path=/usr/lib/nginx/modules
--conf-path=/etc/nginx/nginx.conf
--error-log-path=/var/log/nginx/error.log
--http-log-path=/var/log/nginx/access.log
--pid-path=/var/run/nginx.pid
--lock-path=/var/run/nginx.lock
--http-client-body-temp-path=/var/cache/nginx/client_temp
--http-proxy-temp-path=/var/cache/nginx/proxy_temp
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp
--http-scgi-temp-path=/var/cache/nginx/scgi_temp
--user=nginx
--group=nginx
--without-http_ssi_module
--without-http_userid_module
--without-http_access_module
--without-http_auth_basic_module
--without-http_mirror_module
--without-http_autoindex_module
--without-http_geo_module
--without-http_split_clients_module
--without-http_referer_module
--without-http_rewrite_module
--without-http_proxy_module
--without-http_fastcgi_module
--without-http_uwsgi_module
--without-http_scgi_module
--without-http_grpc_module
--without-http_memcached_module
--without-http_limit_conn_module
--without-http_limit_req_module
--without-http_empty_gif_module
--without-http_browser_module
--without-http_upstream_hash_module
--without-http_upstream_ip_hash_module
--without-http_upstream_least_conn_module
--without-http_upstream_keepalive_module
--without-http_upstream_zone_module
--without-http_gzip_module
--with-http_gzip_static_module
--with-threads
--with-compat
--with-file-aio
--add-dynamic-module=/usr/src/ngx_brotli-$NGX_BROTLI_VERSION
"
# Собираем
&& ./configure $CNF
&& make -j$(getconf _NPROCESSORS_ONLN)
&& make install
&& rm -rf /usr/src/
# Удаляем динамический brotli модуль, оставляя только статический
&& rm /usr/lib/nginx/modules/ngx_http_brotli_filter_module.so
&& sed -i '$ d' /etc/apk/repositories
# Bring in gettext so we can get `envsubst`, then throw
# the rest away. To do this, we need to install `gettext`
# then move `envsubst` out of the way so `gettext` can
# be deleted completely, then move `envsubst` back.
&& apk add --no-cache --virtual .gettext gettext
&& mv /usr/bin/envsubst /tmp/
&& runDeps="$(
scanelf --needed --nobanner /usr/sbin/nginx /usr/lib/nginx/modules/*.so /tmp/envsubst
| awk '{ gsub(/,/, "nso:", $2); print "so:" $2 }'
| sort -u
| xargs -r apk info --installed
| sort -u
)"
&& apk add --no-cache $runDeps
&& apk del .build-deps
&& apk del .gettext
&& mv /tmp/envsubst /usr/local/bin/
# Bring in tzdata so users could set the timezones through the environment
# variables
&& apk add --no-cache tzdata
# forward request and error logs to docker log collector
&& ln -sf /dev/stdout /var/log/nginx/access.log
&& ln -sf /dev/stderr /var/log/nginx/error.log
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
STOPSIGNAL SIGTERM
CMD ["nginx", "-g", "daemon off;"]
Ka whakatika tonu ahau i te nginx.conf kia taea ai te gzip me te brotli ma te taunoa. Ka whakauruhia ano e ahau nga pane keteroki, na te mea kare rawa tatou e huri i te pateko. A ko te pa whakamutunga ko te whakahoki i nga tono 404 katoa ki te index.html, he mea tika tenei mo te whakatere i te SPA.
nginx.conf
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
load_module /usr/lib/nginx/modules/ngx_http_brotli_static_module.so;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
gzip_static on;
brotli_static on;
server {
listen 80;
server_name localhost;
charset utf-8;
location / {
root html;
try_files $uri /index.html;
etag on;
expires max;
add_header Cache-Control public;
location = /index.html {
expires 0;
add_header Cache-Control "no-cache, public, must-revalidate, proxy-revalidate";
}
}
}
}
Ka taea e koe te tango i te ahua kua oti i konei:
Te whakaako i nga tatauranga ki te mohio ki nga taurangi taiao
He aha pea te take e hiahiatia ana i roto i te SPA? Hei tauira, hei tohu ko tehea API RESTful hei whakamahi. Ko te tikanga, ka whakawhitia nga tautuhinga mo te taiao e hiahiatia ana ki te SPA i te wa hanga. Mena ka hiahia koe ki te whakarereke i tetahi mea, me hanga ano e koe te tono. Kaore au e hiahia. E hiahia ana ahau kia hanga kotahi te tono i te atamira CI, me te whirihora i nga mea e tika ana i te atamira CD ma te whakamahi i nga taurangi taiao.
Ae ra, ko nga konae pateko kaore e mohio ki nga taurangi taiao. Na reira, ka whai koe ki te whakamahi i te tinihanga. I te ahua whakamutunga, kaore au e whakarewa i te nginx, engari he tuhinga anga motuhake ka panui i nga taurangi o te taiao, tuhia ki nga konae pateko, ka kopirihia, katahi ka whakawhiti te mana ki te nginx.
Mo tenei kaupapa, ka tukuna e te Dockerfile te tawhā ENTRYPOINT. Me hoatu ki a ia te tuhinga e whai ake nei (ma te Angular hei tauira):
docker-entrypoint.sh
#!/bin/sh set -e FLAG_FILE="/configured" TARGET_DIR="/etc/nginx/html" replace_vars () { ENV_VARS='$(awk 'BEGIN{for(v in ENVIRON) print "
quot;v}')'
# В Angular ищем плейсхолдеры в main-файлах
for f in "$TARGET_DIR"/main*.js; do
# envsubst заменяет в файлах плейсхолдеры на значения из переменных окружения
echo "$(envsubst "$ENV_VARS" < "$f")" > "$f"
done
}
compress () {
for i in $(find "$TARGET_DIR" | grep -E ".css$|.html$|.js$|.svg$|.txt$|.ttf
quot;); do
# Используем максимальную степень сжатия
gzip -9kf "$i" && brotli -fZ "$i"
done
}
if [ "$1" = 'nginx' ]; then
# Флаг нужен, чтобы выполнить скрипт только при самом первом запуске
if [ ! -e "$FLAG_FILE" ]; then
echo "Running init script"
echo "Replacing env vars"
replace_vars
echo "Compressing files"
compress
touch $FLAG_FILE
echo "Done"
fi
fi
exec "$@"
Kia taea ai e te tuhinga te mahi, me tuhi nga tautuhinga ki nga konae js i tenei puka:${API_URL}
.Me mahara ko te nuinga o nga SPA hou e taapiri ana i nga tohu ki o raatau konae i te wa e hanga ana. He mea tika tenei kia taea e te kaitirotiro te keteroki i te konae mo te wa roa. Mena ka huri te konae, ka huri tona hash, ka kaha te kaitirotiro ki te tango ano i te konae.
Engari, i roto i taku tikanga, ko te whakarereke i te whirihoranga na roto i nga taurangi taiao e kore e arai i te huringa o te hash file, ko te tikanga me whakakorehia te keteroki tirotiro i etahi atu huarahi. Kaore au i tenei raru na te mea ka tukuna nga whirihoranga rereke ki nga taiao rereke.
Te whakakotahi i te ahua whakamutunga
Ka mutu.
Dockerfile
# Первый базовый образ для сборки FROM alexxxnf/spa-builder as builder # Чтобы эффктивнее использовать кэш Docker-а, сначала устанавливаем только зависимости COPY ./package.json ./package-lock.json /app/ RUN cd /app && npm ci --no-audit # Потом собираем само приложение COPY . /app RUN cd /app && npm run build -- --prod --configuration=docker # Второй базовый образ для раздачи FROM alexxxnf/nginx-spa # Забираем из первого образа сначала компрессор COPY --from=builder /usr/local/bin/brotli /usr/local/bin # Потом добавляем чудо-скрипт COPY ./docker/docker-entrypoint.sh /docker-entrypoint.sh # И в конце забираем само приложение COPY --from=builder /app/dist/app /etc/nginx/html/ ENTRYPOINT ["/docker-entrypoint.sh"] CMD ["nginx", "-g", "daemon off;"]
Inaianei ka taea te whakaemi me te whakamahi i te ahua ki hea.
Source: will.com