Preface
According to project requirements, when implementing the logout function, different logout URLs need to be called according to the test environment and the production environment. This article will introduce how to set variables in Docker front-end image and how to use variables.
Solution
During the stage of generating the front-end container, you can use the same image to pass in parameters according to different environments to create different front-end containers. Here is an example of dynamically inserting and using variables during the container execution phase.
step
1. Create a file in the root directory, the file content is as follows:
#!/usr/bin/env sh cat /etc/nginx/ nginx -g "daemon off;"
Note: #!/usr/bin/env sh does not mean the meaning of annotation, but the meaning of choosing the compiled language. It is recommended to use sh because bash may not be installed on every server.
Note: Why add nginx -g "daemon off;"?
Because to make the container run continuously, there must be a foreground process, here nginx is converted into a foreground process.
2. Copy in Dockerfile and copy it from outside the container to inside the container:
... COPY /app/
3. Create a file in the root directory, first copy the code from, and then add the ENV_VARS placeholder under http -> server of the file. The code is as follows:
http { ... server { ..... location / { default_type application/json; return 200 '${ENV_VARS}'; } } }
4. Create a method to get variables on the server side of the project, the code is as follows:
type Env = { logoutUrl?: string; }; export async function getEnvironmentVariables() { return request<Env>('/', { method: 'GET' }); }
5. Add a method to use variables in the project code, the code is as follows:
const logout = () => { getEnvironmentVariables() .then((data) => { const logoutUrl = data?.logoutUrl; if (logoutUrl) { ... } }) .catch((e) => { ... }); };
6. After the image is built normally, when generating the container, you can replace the ENV_VARS string in the original front-end file by passing parameters through environment variables:
docker run -e ENV_VARS='{"logoutUrl": "xxxxxx"}' --name test -p 81:8000 -itd :v0.0.31 sh
Note: If the replaced environment variable is in JSON format, you need to include the variable value in single quotes and the attribute value in the variable value in double quotes. For example: ENV_VARS='{"logoutUrl": "xxxxxx"}'
Submission
This design allows the decoupling of the address through environment variables during front-end independent container deployment, avoiding the workload of building mirrors again and again.
This is the article about how to dynamically insert and use variables in front-end projects. For more information about Docker's front-end insertion and use variables, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!