在docker中运行React实例之前运行bash脚本

在docker中运行React实例之前运行bash脚本

本文介绍了在docker中运行React实例之前运行bash脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在初始化CRA应用程序之前在初始化时在Docker容器中运行bash脚本.此bash脚本将环境变量 GCP_PROJECT_ID 复制到 docker-entrypoint.sh 文件所定义的 .env 文件中.我尝试使用 Entrypoint 来运行文件,但是它不起作用.

I'm trying to run a bash script in a docker container on initialization when the container runs before starting a CRA application. This bash script copies an environment variable GCP_PROJECT_ID to a .env file as defined by the docker-entrypoint.sh file. I tried using an Entrypoint to run the file but it doesn't work.

Dockerfile

FROM node:9-alpine

RUN npm install yarn

WORKDIR /usr/app

COPY ./yarn.lock /usr/app
COPY ./package.json /usr/app

RUN yarn install

COPY . /usr/app/

RUN yarn build

FROM node:9-alpine
WORKDIR /usr/app

COPY --from=0 /usr/app/build /usr/app/build
COPY --from=0 /usr/app/package.json /usr/app/package.json
COPY .env /usr/app/.env
COPY docker-entrypoint.sh /usr/app/docker-entrypoint.sh
RUN chmod +x /usr/app/docker-entrypoint.sh

RUN yarn global add serve

RUN npm prune --production
ARG GCP_PROJECT_ID=xxxxx # SAMPLE ENVIRONMENT VARIABLES
ENV GCP_PROJECT_ID=$GCP_PROJECT_ID

ENTRYPOINT [ "/usr/app/docker-entrypoint.sh" ]
CMD [ "serve", "build" ]

docker-entrypoint.sh

#!/bin/sh
printf "\n" >> /usr/app/.env
printf "REACT_APP_GCP_PROJECT_ID=$GCP_PROJECT_ID" >> /usr/app/.env

我可以验证环境变量是否存在,即运行 docker run -it --entrypoint sh< IMAGE NAME> echo $ GCP_PROJECT_ID 确实会打印xxxxx .

I can verify that the environment variables do exist i.e. running docker run -it --entrypoint sh <IMAGE NAME> and echo $GCP_PROJECT_ID does print xxxxx.

在docker中启动CRA应用程序之前,如何运行bash脚本?

How can I run a bash script before starting up my CRA application in docker?

推荐答案

ENTRYPOINT 脚本通过 CMD 作为参数传递.您需要包括一行以告知其实际运行命令的路径,通常是 exec"$ @" .

The ENTRYPOINT script gets passed the CMD as arguments. You need to include a line to tell it to actually run the command, typically exec "$@".

#!/bin/sh
if [ -n "$GCP_PROJECT_ID" ]; then
  echo "REACT_APP_GCP_PROJECT_ID=$GCP_PROJECT_ID" >> /usr/app/.env
fi
exec "$@"

如果使用此模式,则不需要-entrypoint

If you use this pattern, you don't need --entrypoint

sudo docker run -e GCP_PROJECT_ID=... imagename cat /usr/app/.env
# should include the REACT_APP_GCP_PROJECT_ID line

根据文件中的其他内容,通常使用 docker run -v 整体注入配置文件,而不是尝试在启动时进行构造.

Depending on what else is in the file, it's common enough to use docker run -v to inject a config file wholesale, instead of trying to construct it at startup time.

sudo docker run -v $PWD/dot-env:/usr/app/.env imagename

这篇关于在docker中运行React实例之前运行bash脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 07:09