docker: add runtime config injection from env

This commit is contained in:
Patrik Oldsberg
2020-06-07 14:36:05 +02:00
parent 650779412c
commit fe2d04ae3b
2 changed files with 34 additions and 0 deletions
+2
View File
@@ -5,6 +5,8 @@ FROM nginx:mainline
# The safest way to build this image is to use `yarn docker-build`
RUN apt-get update && apt-get -y install jq && rm -rf /var/lib/apt/lists/*
COPY packages/app/dist /usr/share/nginx/html
COPY docker/default.conf.template /etc/nginx/conf.d/default.conf.template
COPY docker/run.sh /usr/local/bin/run.sh
+32
View File
@@ -1,9 +1,41 @@
#!/usr/bin/env bash
set -Eeuo pipefail
# Run nginx as root
sed -i 's/user nginx.*$//' /etc/nginx/nginx.conf
# Write selected env vars to nginx config
envsubst '$PORT' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf
# Inject runtime config into the client
function inject_config() {
# Read runtime config from env in the same way as the @backstage/config-loader package
local config
config="$(jq -n 'env |
with_entries(select(.key | startswith("APP_CONFIG_")) | .key |= sub("APP_CONFIG_"; "")) |
to_entries |
reduce .[] as $item (
{}; setpath($item.key | split("_"); $item.value | fromjson)
)')"
>&2 echo "Runtime app config: $config"
local main_js
main_js="$(ls /usr/share/nginx/html/main.*.chunk.js)"
echo "Writing runtime config to ${main_js}"
# escape ' and " twice, for both sed and json
local config_escaped_1
config_escaped_1="$(echo "$config" | jq -cM . | sed -e 's/[\\"\x27]/\\&/g')" # \x27 = '
# escape / and & for sed
local config_escaped_2
config_escaped_2="$(echo "$config_escaped_1" | sed -e 's/[\/&]/\\&/g')"
# Replace __APP_INJECTED_RUNTIME_CONFIG__ in the main chunk with the runtime config
sed -e "s/__APP_INJECTED_RUNTIME_CONFIG__/$config_escaped_2/" -i "$main_js"
}
inject_config
exec nginx -g 'daemon off;'