Try to implement nginx to route between frontend and backend

master
Jason Zhu 2023-05-04 22:53:28 +10:00
parent 17f624e7e6
commit 1d3263c598
10 changed files with 122 additions and 0 deletions

4
eg3/README.md 100644
View File

@ -0,0 +1,4 @@
# e.g. 3: Create an Ningx Reverse Proxy With Docker
How To Run Multiple Docker Containers Under One URL

View File

@ -0,0 +1,5 @@
FROM node:10.15.3-alpine
WORKDIR /home/node/
RUN npm install express --save
COPY index.js .
CMD [ "node", "index.js"]

View File

@ -0,0 +1,8 @@
version: '3.8'
services:
backend:
container_name: backend
build: .
ports:
- "5000:5000"

View File

@ -0,0 +1,7 @@
const express = require('express');
const app = express();
const port = 5000;
const version = '1.0.0';
app.get('/', (req, res) => res.send({ version }));
app.listen(port, () => console.log(`Listening on port ${port}`));

View File

@ -0,0 +1,4 @@
FROM nginx:stable-alpine
WORKDIR /usr/share/nginx/html
RUN apk add curl
COPY index.html .

View File

@ -0,0 +1,8 @@
version: '3.8'
services:
frontend:
container_name: frontend
build: .
# ports:
# - "80:80"

View File

@ -0,0 +1,27 @@
<!DOCTYPE html>
<html>
<head>
<title>Frontend</title>
<script>
window.onload = function () {
fetch('/api', { method: 'get'}).then((response) => {
const json = response.json();
if (response.ok) {
return json;
}
return Promise.reject(new Error('Something went wrong.'));
})
.then((response) => {
document.getElementById('version').innerHTML = JSON.stringify(response);
}).catch((error) => {
document.getElementById('error').innerHTML = error && error.message || 'Something else went wrong.';
});
};
</script>
</head>
<body>
<h1>My Application Version</h1>
<p id="version"></p>
<p id="error"></p>
</body>
</html>

View File

@ -0,0 +1,4 @@
FROM nginx:stable-alpine
WORKDIR /etc/nginx/conf.d
COPY default.conf .
CMD [ "nginx", "-s", "reload"]

View File

@ -0,0 +1,47 @@
server {
listen 80;
listen [::]:80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
proxy_pass http://frontend;
}
location /api {
proxy_pass http://backend:5000/;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}

View File

@ -0,0 +1,8 @@
version: '3.8'
services:
proxy:
container_name: proxy
build: .
ports:
- "80:80"