feat: nextjs runtime read env var

This commit is contained in:
sljeff 2022-08-14 11:39:15 +08:00
parent 96a7bafbb3
commit a23ed0ffbe
5 changed files with 45 additions and 1 deletions

View File

@ -21,6 +21,7 @@ FROM deps as build
WORKDIR /app
COPY --from=deps /app /app
COPY ./deploy/env.production .env.production
ENV NEXT_TELEMETRY_DISABLED 1
ENV NODE_ENV production
@ -36,6 +37,11 @@ WORKDIR /app
COPY --from=build /app/.next/standalone /app
COPY --from=build /app/public /app/public
COPY --from=build /app/.next/static /app/.next/static
COPY ./deploy/entrypoint.sh .
# to identify all the configuration
COPY ./deploy/env.production .env.production
RUN ["chmod", "+x", "./entrypoint.sh"]
ENTRYPOINT ["./entrypoint.sh"]
CMD ["pnpm", "start"]

31
deploy/entrypoint.sh Normal file
View File

@ -0,0 +1,31 @@
#!/bin/bash
# no verbose
set +x
# config
envFilename='.env.production'
nextFolder='./.next/'
function apply_path {
# read all config file
while read line; do
# no comment or not empty
if [ "${line:0:1}" == "#" ] || [ "${line}" == "" ]; then
continue
fi
# split
configName="$(cut -d'=' -f1 <<<"$line")"
configValue="$(cut -d'=' -f2 <<<"$line")"
# get system env
envValue=$(env | grep "^$configName=" | grep -oe '[^=]*$');
# if config found
if [ -n "$configValue" ] && [ -n "$envValue" ]; then
# replace all
echo "Replace: ${configValue} with: ${envValue}"
find $nextFolder \( -type d -name .git -prune \) -o -type f -print0 | xargs -0 sed -i "s#$configValue#$envValue#g"
fi
done < $envFilename
}
apply_path
echo "Starting Nextjs"
exec "$@"

7
deploy/env.production Normal file
View File

@ -0,0 +1,7 @@
# https://github.com/vercel/next.js/discussions/17641
# https://raphaelpralat.medium.com/system-environment-variables-in-next-js-with-docker-1f0754e04cde
NEXT_PUBLIC_APP_NAME=APP_NEXT_PUBLIC_APP_NAME
NEXT_PUBLIC_OUR_DOMAIN=APP_NEXT_PUBLIC_OUR_DOMAIN
NEXT_PUBLIC_DISCORD_LINK=APP_NEXT_PUBLIC_DISCORD_LINK
NEXT_PUBLIC_GITHUB_LINK=APP_NEXT_PUBLIC_GITHUB_LINK
REDIS_URL=APP_NEXT_REDIS_URL

View File

@ -25,7 +25,6 @@ spec:
- image: $IMAGE_TAG_RELEASE
imagePullPolicy: Always
name: xlog
command: ["npm", "run", "start"]
envFrom:
- secretRef:
name: xlog

View File

@ -1,3 +1,4 @@
# Remember to add it in env.production because it is the nextjs project
apiVersion: v1
stringData:
NEXT_PUBLIC_APP_NAME: xlog