I have an Express JS Angular application that I am deploying to ECS Fargate. The application has a couple of process.env.ENVS
that I need to pass into the application code through the Docker container. Initially I thought I can use envsubst
to pass in these variables into the JS files that are using the variables, but it turns out after the container is created the values do not get read in appropriately. I then discovered there is a certain method of passing in environment variables to a containerized application. This method also uses nginx
to host the application. I followed this tutorial. Below is my dockerfile:
FROM xxxx.dkr.ecr.us-east-1.amazonaws.com/ecr/base:latest AS builder
WORKDIR /app
COPY . /app
RUN npm install
RUN npm run build
FROM nginx:latest
COPY --from=builder /app/dist/ /usr/share/nginx/html
CMD ["/bin/sh", "-c", "envsubst < /usr/share/nginx/html/assets/env.template.js > /usr/share/nginx/html/assets/env.js && exec nginx -g 'daemon off;'"]
The problem I’m having is in Fargate after the container deploys I am getting the following error in the logs:
2023/02/13 16:39:31 [error] 9#9: *4 open() "/usr/share/nginx/html/.env" failed (2: No such file or directory), client: 10.18.0.58, server: localhost, request: "GET /.env HTTP/1.1", host: "xx.xx.xx.xx"
It’s saying a .env
file does not exist in the nginx directory. That is correct that a .env
does not exist. It is supposed to be looking for either env.template.js
or env.js
depending on where in the envsubst
command it is in.
Any ideas where I went wrong would be appreciated. Please let me know if anything is missing from this post that is needed. Thanks!
2
Answers
Substitute the contents of the env.template.js file into an env.js file, you should modify the Dockerfile.
Dockerfile
According to the Dockerfile you submitted, the envsubst command is performing the following task: it reads
env.template.js
and outputs the result to/usr/share/nginx/html/assets/env.js
However, the error message in the logs suggests that your application is attempting to access the file
/.env
. This discrepancy between the expected file and the file being accessed by the application is the root cause of the issue.To resolve the problem, you have two options:
Modify the logic of your application so that it loads the correct file, i.e.
/usr/share/nginx/html/assets/env.js
.Change the file that
envsubst
is redirecting its output to so that it matches the file being accessed by your application, i.e/usr/share/nginx/html/assets/.env
.