Nginx server goes down constantly when redeploying React application? - reactjs

I am deploying my code onto a nginx server from Jenkins I have being following this process for a few months. There is a build script on my server box that a job configured in Jenkins picks up to know when pull down my latest changes and re build. In my nginx configuration looks like below. So you see currently getting the build folder in my root. And my build script just cp /var/www/example , npm run build, and nginx restart . Like I know the issue but Im getting confused on the proper steps to take because nginx shouldn't be getting my build folder while this script is running which is the reason im seeing 500 internal server errors whenever i run the Jenkins job.
server_name example.com www.example.com;
#return 301 https://$host$request_uri;
#ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
#ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
#include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
#ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
root /var/www/example/build/;
index index.html;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
location / {
try_files $uri $uri/ /index.html;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js|eot|ttf|woff|woff2)$ {
expires max;
add_header Cache-Control public;
add_header Access-Control-Allow-Origin *;
access_log off;
try_files $uri $uri/ /index.html;
}

Related

My website is not loading the same page when i refresh the page

I have deployed multiple reactapps using docker and nginx as reverse proxy.
My Docker file is same for seperate 3 react apps!!
FROM node:16-alpine
WORKDIR /app
COPY package.json ./
COPY package-lock.json ./
COPY ./ ./
RUN npm i
CMD ["npm", "run", "start"]
My nginx.conf
server {
listen 80;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
add_header 'Cache-Control' "public, max-age=31536000";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options: "nosniff";
ssl_certificate /etc/nginx/conf.d/cert.crt;
ssl_certificate_key /etc/nginx/conf.d/ssl.key;
server_name <my-ip-address>;
location / {
proxy_pass http://172.17.0.5:3000;
#try_files $uri /index.html;
}
location /qae {
proxy_pass http://172.17.0.2:3001;
#try_files $uri /index.html;
}
location /qac {
proxy_pass http://172.17.0.4:3002;
#try_files $uri /index.html;
}
}
This code is running fine and my reactapps are opening on this, but when i login into my website and try reloading my page its redirecting to 404 error page.
When i remove the hashtag for try_files $uri /index.html; iam getting 500 internal server error.
Solution needed : When i refresh the reactapp it has to stay on the same page.
Iam using 3 different images for 3 reactapps and also nginx is seperate image and making proxy_pass for 3 containers.
Hosting react files under nginx should just be a matter of copying all the files into the document root directory. Something like (loosely based on this article):
mkdir -p /var/www/my_site
cd /home/me/react1
npm run build
cp -r ./build/* /var/www/my_site/
mkdir -p /var/www/my_site/qae
cd /home/me/react2
npm run build
cp -r ./build/* /var/www/my_site/qae/
mkdir -p /var/www/my_site/qac
cd /home/me/react3
npm run build
cp -r ./build/* /var/www/my_site/qac/
Then in your nginx conf you would need different try_files rules for each subdirectory so that each one would use the correct index.html. (Loosely based on this answer):
root /var/www/my_site;
location / {
try_files $uri /index.html;
}
location /qae {
try_files $uri /qae/index.html;
}
location /qac {
try_files $uri /qac/index.html;
}

Nginx React App - Allowing only one location to be accessible

I have a server on DigitalOcean that hosts my web app.
The server hosts the API (using Flask) and my web app (React).
I managed to set up the Nginx to serve the app and the API using 2 different domains.
Now I'm facing a problem.
I'm, trying to add another domain that I need to be able to access only one page in the react app.
I can't find a way to set up the configuration to allow that.
server {
server_name www.domain domain;
root /var/www/path/html;
index index.html index.htm index.nginx-debian.html;
location / { deny all; }
location = / { }
location /test {
try_files $uri /index.html;
}
location /favicon.ico {
try_files $uri /index.html;
}
location /static/ {
try_files $uri /index.html;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/domain/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/domain/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot }
In my other config files I just use try_files $uri /index.html; and it works perfectly.
I need this domain to be able to accept requests for one path only (domain.com/confirm/token)

How to set up nginx config for a React.js app deployed on AWS ECS with path-based routing load balancer

I have an application which consists of two containers:
a backend node.js server on express.js, referred to as 'app-server'
a front-end react.js client based on create-react-app, referred to as 'app-client'. This one uses an nginx server to set up reverse proxy for /api requests to the application - like this post describes
Both are dockerized and deployed on AWS ECS Fargate and are supposed to be hosted on the same domain example.com, just different paths, respectively /app-server and app-client. So the users would access the app via https://example.com/app-client. In the future we would like to host more apps on the same domain using path based routing.
To achieve that we have defined a rule on the Application Load Balancer listener on EC2 which looks like this:
IF
- Path is: /app-client*
- Host is: example.com
THEN
- Forward to
- app-client-service-alb-h: 1 (100%)
- Group-level stickiness: Off
Also tested - Path is: /app-client, without the * at the end.
I managed to adjust the backend express server to work with this scenario but I'm struggling to make the React.js app work with the path forwarding - it just shows a blank page (worked without a problem when it was hosted directly on a domain, let's say http://app-client.com).
My guess is it has something to do with the nginx config because the request URL's are correct but there are just no .html, .js and .css files there.
Dockerfile looks like this:
FROM node:11.5.0 as builder
WORKDIR /usr/src/app
ADD ./ /usr/src/app
RUN npm install && \
npm run build
# ------------------------------------------------------
# Production Build
# ------------------------------------------------------
FROM nginx:1.16.0-alpine
COPY --from=builder /usr/src/app/build/ /usr/share/nginx/html
RUN rm -rf /etc/nginx/conf.d
COPY conf /etc/nginx
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Nginx config is set up this way:
server {
listen 80;
server_name example.com;
location /api {
proxy_pass https://example.com/app-server;
proxy_pass_request_headers on;
}
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
React app's package.json file was adjusted by adding homepage setting:
"homepage": "/app-client"
Also tried with "homepage": "https://example.com/app-client". In both scenarios requested paths look correct, for example:
https://example.com/app-client/static/js/main.32859df6.chunk.js
The problem is that there is nothing found under this address, the page is blank. That's why I am assuming that nginx config needs to be adjusted to provide the file from correct location but have no idea what to adjust (I did also test removing the "homepage" from package.json but that also didn't solve it.).
I tried changing the location to location /app-client { or location ^~ /app-client { but that didn't work:
location /app-client {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
I blindly followed many other solutions, for example:
Nginx Meets Amazon ECS: Hosting Multiple Back-End Services Using a Single Load Balancer
Based on this config
None of them fixed the problem and I'm a rookie in that area so I'm stuck... Please help :(
------- Edited -------
The issue is solved and I'm posting the answer in case someone else finds it helpful.
The Nginx config should look like this, with appropriate rewrite defined:
server {
listen 80;
# All files should be at this directory; put it above location, otherwise it was looking in a wrong directory somewhere in `/etc/...`
root /usr/share/nginx/html;
# Prefix app-client -> rewrite
location /app-client {
rewrite ^/app-client(?:/(.*))?$ /$1;
}
# proxy for backend server /api requests
location /api {
# the ending `/api` part depends on whether your server routes also start with `/api` or not, mine do hence it was required
proxy_pass https://example.com/app-server/api;
proxy_pass_request_headers on;
}
location / {
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
}
The issue is solved and I'm posting the answer in case someone else finds it helpful.
The Nginx config should look like this, with appropriate rewrite defined:
server {
listen 80;
# All files should be at this directory; put it above location, otherwise it was looking in a wrong directory somewhere in `/etc/...`
root /usr/share/nginx/html;
# Prefix app-client -> rewrite
location /app-client {
rewrite ^/app-client(?:/(.*))?$ /$1;
}
# proxy for backend server /api requests
location /api {
# the ending `/api` part depends on whether your server routes also start with `/api` or not, mine do hence it was required
proxy_pass https://example.com/app-server/api;
proxy_pass_request_headers on;
}
location / {
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
}
Here is an example of my microservices application hosted on AWS with ALB & ECS.
ECS has multiple backend services, react app static files being served from frontend container service which is NGINX reverse proxy.
NGINX_ALB is the ALB DNS name stored in env variable inside container during Dockerfile build.
Gets substituted into nginx config using:
CMD ["/bin/sh", "-c", "export NGINX_ALB && envsubst '$$NGINX_ALB' < /etc/nginx/conf.d/nginx.conf.template > /etc/nginx/conf.d/nginx.conf && nginx -g 'daemon off;'"]
upstream alb {
least_conn;
server ${NGINX_ALB}:80 max_fails=3;
}
server {
# ref https://www.veggiespam.com/bad-headers/
proxy_hide_header Server;
proxy_hide_header X-Powered-By;
proxy_hide_header X-AspNetMvc-Version;
proxy_hide_header X-AspNet-Version;
proxy_hide_header X-Drupal-Cache;
proxy_hide_header X-Drupal-Dynamic-Cache;
proxy_hide_header X-Generator;
proxy_hide_header X-Runtime;
proxy_hide_header X-Rack-Cache;
# proxy_set_headers moved to server directive allowing them to be referenced by all locations
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 300s;
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /auth/ {
proxy_pass http://alb;
proxy_redirect off;
}
location /api/sigma {
proxy_pass http://alb;
proxy_redirect off;
}
location /api/ {
proxy_pass http://alb;
proxy_redirect off;
}
location /db {
proxy_pass http://alb;
proxy_redirect off;
}
location /scheduler {
proxy_pass http://alb;
proxy_redirect off;
}
location /validator {
proxy_pass http://alb;
proxy_redirect off;
}
location /alarm/ {
proxy_pass http://alb;
proxy_redirect off;
}
location /reporter {
proxy_pass http://alb;
proxy_redirect off;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}

Deploy Laravel and React spa

How can I deploy these two together, I don't like the Laravel React preset, I want to separate both, bundle the React app and deploy them together with any web server (apache, nginx...)
EDIT
This is my config for Laravel, but it isn't loading the routes
server {
listen 8000;
server_name 127.0.0.1
root "..\..\Proyecto\Backend\JWT\public";
add_header 'Access-Control-Allow-Origin' '*';
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
index index.html index.htm index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
You can run them separately using nginx
you run each on separate ports and use methods (POST/GET) to push/get data
use pm2 (http://pm2.keymetrics.io/) for running React (I recommend it because you can monitor the activity of the react app and if you want to do maintenance you can stop the current app process and run a "under maintenance" app process)
you can read more about running laravel on nginx here (https://www.digitalocean.com/community/tutorials/how-to-deploy-a-laravel-application-with-nginx-on-ubuntu-16-04)
as for running react without pm2, you have to build the project yarn build and tell nginx that the file you want to load is the index.html inside of the build file
assuming that you are using an ubuntu server and you uploaded your code to github or gitlab
server {
listen 50;
root /var/www/[Your repo name]/build;
server_name [your.domain.com] [your other domain if you want to];
index index.html;
location / {
try_files $uri /index.html;
}
}
you write this inside of your nginx configuration along with the laravel configuration on a separate port
hope my answer helped a bit
This was proving to be very tricky and it took me at least 3 days to put everything together. Here is what you have to do.
Run
npm run build in the react project.
Copy the contents of the build folder to the server
scp react_project/build/* <server name or ip>:/var/www/html/react
Change the ownership of the project folders to the user www-data or add your user id to the group www-data.
Now. set up the Laravel project in a different directory (in /var/www/html/laravel, for example).
Set up the database, environment variables.
Run
php artisan key:generate
php artisan config:clear
php artisan config:cache
Now, proceed with nginx configuration. Create 2 configs for react and laravel projects as given below. Make sure that the listen ports are different for both projects.
Create configuration files for react and laravel projects under /etc/nginx/sites-available
Create symlinks to the created configs under /etc/nginx/sites-enabled as given below
sudo ln -s /etc/nginx/sites-available/react_conf /etc/nginx/sites-enabled/react_conf
sudo ln -s /etc/nginx/sites-available/laravel_conf /etc/nginx/sites-enabled/laravel_conf
And for the contents,
react_conf:
server {
listen 80;
server_name <server_ip or hostname>;
charset utf-8;
root /var/www/html/react;
index index.html index.htm;
# Always serve index.html for any request
location / {
root /var/www/html/react;
try_files $uri /index.html;
}
error_log /var/log/nginx/react-app-error.log;
access_log /var/log/nginx/react-app-access.log;
}
laravel_conf:
server {
listen 90;
server_name <server ip or hostname>;
charset utf-8;
root /var/www/html/laravel/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
index index.php index.html index.htm;
# Always serve index.html for any request
location /api {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
error_log /var/log/nginx/laravel-app-error.log;
access_log /var/log/nginx/laravel-app-access.log;
}
Now, delete the default config present in /etc/nginx/sites-enabled
Also, verify that /etc/nginx/nginx.conf contains the following include directive where the server configs are expected(under http)
include /etc/nginx/sites-enabled/*;
Verify that the config is fine by running
sudo nginx -t
Restart the server
sudo service nginx restart
Now, you should be up and running.
You can approach it by two ways .
First one is when the you are creating react-app in different folder than the laravel project folder . In such case just deploy laravel app and react app in two different url .
The second condition is when the react-app is inside the laravel app . In such case build the react project and put the dist folder in views folder of the laravel project . So in routes/web.php add this
//Used for handling the html file of react project
View::addExtension('html', 'php');
Route::get('/{any}', function () {
//path to dist folder index.html inside the views directory
return view('build/index');
})->where('any', '.*');
Laravel will not server the required js and css file from inside the views folder . So you need copy and paste all the content of the dist folder to public folder of the laravel project . No need to copy paste index.html file but other file need to placed in the pubic folder .
After that visit the root url of the laravel project in the browser the react app should be working

Bug in react app only present on nginx webserver, not localhost

in my react app I've been struggling with a bug that made a map the wrong size on the page. After solving the bug yesterday I've been trying to make the solution work on my server. Using Ubuntu 16.04 with Nginx as the webserver serving my /build folder. I tried 'hard resetting' the page by deleting the entire website folder from /var/www, re-cloning from githug and running yarn build again, how ever the bug is still present; but not present in localhost.
My nginx config
server {
root /var/www/<sitepath>/build;
server_name <siteurl .;
index index.html index.htm;
location / {
try_files $uri /index.html;
auth_basic "This site is under development";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location ~* \.(?:manifest|appcache|html?|xml|json)$ {
expires -1;
}
location ~* \.(?:css|js)$ {
try_files $uri =404;
expires 1y;
access_log off;
add_header Cache-Control "public";
}
listen 443 ssl; # managed by Certbot
ssl_certificate <pempath>; # managed by Certbot
ssl_certificate_key <pempath>; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam <pempath>; # managed by Certbot
}
server {
if ($host = <mysite>) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = <mysite>) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
server_name <mysite>;
return 404; # managed by Certbot
}
The rest of the site seems to be working fine, I'm only using nginx as my webserver, no node is being used. I've tried using chrome incognito mode and tested on laptops that have never opened the page before, but the bug is still present. The app was made using create-react-app, I have not ejected the create-react-app. for running the app localhost I've been using yarn run
site on the server:
site on server
site on localhost
site on localhost
I'd be happy to post any additional config or code that may help solving this issue.
edit:
I've tried doing the same process with deleting the website folder and re-cloning localhost to see if the issue was present then, it was not.

Resources