nextjs+Dockerfile:env变量传递到nextjs.config.js

jfewjypa  于 2023-06-05  发布在  Docker
关注(0)|答案(2)|浏览(166)

我有一个next.config.js

module.exports = {
  .........
  env: {
    BASE_URL: 'http://xx.xx.xx.xx:8000',
  },
  ............
};

现在我想在构建docker镜像时更改BASE_URL
我的Dockerfile文件

FROM node:16-alpine3.14

WORKDIR /usr/app

COPY ./package.json ./

RUN yarn install

ENV BASE_URL=http://yy.yyy.yy.yy:80

# Copy all files
COPY ./ ./

RUN yarn build

因此,在Dockerfile中传递ENV BASE_URL=http://yy.yyy.yy.yy:80将有助于更改next.config.js中的BASE_URL: 'http://xx.xx.xx.xx:8000'
或者我可以改变BASE_URL的方式

j0pj023g

j0pj023g1#

docker文件中的ENV BASE_URL=http://yy.yyy.yy.yy:80将设置一个环境变量BASE_URL为其值,您需要读取该变量。

//next.config.js
module.exports = {
  .........
  env: {
    BASE_URL: process.env.BASE_URL || 'http://xx.xx.xx.xx:8000', //read the value from env id empty use default value.
  },
  ............
};
iyzzxitl

iyzzxitl2#

创建了一个entrypoint.sh文件,并将以下脚本放入其中:

#!/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 "$@"

下面是我的Dockerfile引用entrypoint.sh文件

# 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

由next.config.js修改,按照以下方式定义环境变量:

publicRuntimeConfig: {
      // Will be available on both server and client
      API_URL: process.env.API_URL,
  },

相关问题