Service
cnpm i -g egg-init
Service1
egg-init egg-example1 --type=simple && cd egg-example1
cnpm i
vim app/router.js
'use strict';
module.exports = app => {
const { router, controller } = app;
router.get('/test1', controller.home.index);
};
vim app/controller/home.js
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
this.ctx.body = 'hi, egg' + ' from example1';
}
}
module.exports = HomeController;
cnpm start
# [egg-scripts] egg started on http://127.0.0.1:7001
curl localhost:7001/test1
# hi, egg from example1
Service2
egg-init egg-example2 --type=simple && cd egg-example2
cnpm i
vim app/router.js
'use strict';
module.exports = app => {
const { router, controller } = app;
router.get('/test2', controller.home.index);
};
vim app/controller/home.js
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
this.ctx.body = 'hi, egg' + ' from example2';
}
}
module.exports = HomeController;
cnpm start -- --port=7002
# [egg-scripts] egg started on http://127.0.0.1:7002
curl localhost:7002/test2
# hi, egg from example2
Nginx
sudo apt install -y nginx
sudo vim /etc/nginx/sites-enabled/example.com
server {
listen 80;
server_name kong.com;
location / {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
server {
listen 80;
server_name example1.com;
location / {
proxy_pass http://localhost:7001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
server {
listen 80;
server_name example2.com;
location / {
proxy_pass http://localhost:7002;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
sudo nginx -t
sudo nginx -s reload
sudo sh -c "echo '127.0.0.1 kong.com' >> /etc/hosts"
sudo sh -c "echo '127.0.0.1 example1.com' >> /etc/hosts"
sudo sh -c "echo '127.0.0.1 example2.com' >> /etc/hosts"
curl kong.com
# {"message":"no route and no API found with those values"}
curl example1.com/test1
# hi, egg from example1
curl example2.com/test2
# hi, egg from example2
Kong
sudo kong stop
sudo /usr/local/openresty/nginx/sbin/nginx -p /usr/local/kong -c nginx.conf
curl -i localhost:8001
# HTTP/1.1 200 OK
# Server: kong/0.14.0
浏览器打开localhost:8002添加APIs如下
curl kong.com/test1
# hi, egg from example1
curl kong.com/test2
# hi, egg from example2