Andy asked:
I’m trying to serve some static content produced by running npm run build
with create-react-app. Here’s my nginx default.conf file:
server {
listen 3000;
location / {
root usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
}
Here’s my Dockerfile:
FROM node:14-slim as builder
WORKDIR "/app"
COPY ./package.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx
EXPOSE 3000
COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/build /usr/share/nginx/html
If I look inside my Docker container, I can see the files are all where they should be: https://i.stack.imgur.com/H4hy7.png
Also for context, I’m also using nginx for routing, with this config:
upstream client {
server client:3000;
}
upstream api {
server api:3001;
}
server {
listen 81;
location / {
proxy_pass http://client;
}
location /api {
rewrite /api/(.*) /$1 break;
proxy_pass http://api;
}
location /sockjs-node {
proxy_pass http://client;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
}
However, if I try to navigate to localhost:81, I get this error:
client_1 | 2021/02/18 15:46:35 [error] 28#28: *10 rewrite or internal redirection cycle while internally redirecting to "/index.html", client: 172.18.0.3, server: , request: "GET / HTTP/1.0", host: "client"
Any ideas what the issue could be? Most other threads I’ve looked at focus on this bit, but I already have it and I’m sure the file locations are all correct.:
server {
listen 3000;
location / {
root usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html; <-- this line here
}
}
Another thread suggested adding "homepage": "./
" to the package.json
file, but this didn’t seem to make any difference either.
My answer:
Fix the typo in your root
directive.
root usr/share/nginx/html;
The leading /
is missing, thus nginx considers the path relative to a compiled-in default (usually /etc/nginx
on Linux).
What is actually happening is that the directory /etc/nginx/usr/share/nginx/html
does not exist. So when processing try_files
, nginx first tries $uri
which fails, then it tries $uri/
which processes the paths in the index
directive. None of these exist either. Finally it reaches /index.html
, which it feeds back to try_files
, but as that is the same path it just tried in index
processing, it detects the infinite loop and bails out.
View the full question and any other answers on Server Fault.
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.