I have a Node.js app and an Angular app. I’ve dockerized them. They run in the same container. Nginx serves the Angular app and sends the /api/*
requests to the Node.js server.
It works perfectly when I’m running the container on my local machine. But it doesn’t work on Google Cloud Run. More specifically, I get 502 errors when calling the API endpoints.
I can see this in the GCP logs:
connect() failed (111: Connection refused) while connecting to upstream, client: 169.254.1.1, server: , request: “GET /api/ping HTTP/1.1”
My Dockerfile:
FROM node:20
RUN apt-get update && apt-get install -y nginx
WORKDIR /usr/src/app
COPY . .
RUN npm ci --omit=dev
RUN cd my-project && npm i && npm run build && cd ..
RUN rm /etc/nginx/sites-enabled/default
COPY nginx.conf /etc/nginx/nginx.conf
RUN cp -r ./my-project/dist/my-project/browser/* /usr/share/nginx/html/
CMD npm run pm2:start:prod && nginx -g 'daemon off;'
And the Nginx config:
user root;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
server {
listen 8080;
server_name _;
# Serve static files from the /usr/share/nginx/html directory
location / {
root /usr/share/nginx/html;
try_files $uri $uri/ /index.html;
}
# Proxy requests to /api to the backend server
location /api/ {
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://127.0.0.1:3001;
}
access_log /dev/stdout;
error_log /dev/stderr;
}
}
Interestingly, it used to work without Nginx and with ng serve
that used to proxy requests itself.