Created an entrypoint.sh file and put the below script in it:
#!/bin/bash
# no verbose
set +x
# config
envFilename='.env'
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
echo "***** line ******"
echo $line
# split
configName="$(cut -d'=' -f1 <<<"$line")"
configValue="$(cut -d'=' -f2 <<<"$line")"
echo "**** configName ****"
echo $configName
echo "**** configValue ****"
echo $configValue
# get system env
envValue=$(env | grep "^$configName=" | grep -oe '[^=]*$');
echo "**** envValue ****"
echo $envValue
# 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 *** "
echo $API_URL
exec "$@"
Below is my Dockerfile referencing the entrypoint.sh file
# Dockerfile
# base image
FROM node:alpine
# create & set working directory
RUN mkdir -p /usr/src
WORKDIR /usr/src
# install dependencies
COPY package*.json /usr/src/
RUN npm install
# copy source files
COPY . /usr/src
# start app
RUN npm run build
# Make it executable
RUN apk add --no-cache --upgrade bash
RUN ["chmod", "+x", "/usr/src/entrypoint.sh"]
EXPOSE 3000
# Execute script
ENTRYPOINT ["/usr/src/entrypoint.sh"]
CMD npm run start
Modified by next.config.js to define an environment variable as per the below:
publicRuntimeConfig: {
// Will be available on both server and client
API_URL: process.env.API_URL,
},
.envfile to setup your environment variables instead. See Next.js Environment Variables.