且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在一个EC2实例上运行多个应用程序?

更新时间:2022-05-12 05:54:51

首先,关于在一个盒子上设置多个Web应用程序没有EC2特定要求。您需要在反向代理模式下使用nginx(或Apache)。这样,Web服务器将侦听端口80(和443),而您的应用程序将在其他各种端口上运行。每个传入的请求都读取主机标头,以将请求映射到后端。因此,不同的DNS名称/域将显示不同的内容。

First, there's nothing EC2-specific about setting up multiple web apps on one box. You'll want to use nginx (or Apache) in "reverse proxy" mode. This way, the web server listens on port 80 (and 443), and your apps run on various other ports. Each incoming request reads the "Host" header to map the request to a backend. So different DNS names/domains show different content.

以下是在反向代理模式下设置nginx的方法: http://www.cyberciti.biz/tips/using-nginx-as-reverse-proxy.html

Here is how to setup nginx in reverse proxy mode: http://www.cyberciti.biz/tips/using-nginx-as-reverse-proxy.html

对于每个后端应用,您需要:

For each "back-end" app, you'll want to:

1)分配一个端口(3000个)在这个例子中)

1) Allocate a port (3000 in this example)

2)编写一个上游节,告诉它您的应用程序在哪里

2) write an upstream stanza that tells it where your app is

3)编写一个(虚拟)服务器节,该节从服务器名称映射到上游位置

3) write a (virtual) server stanza that maps from the server name to the upstream location

例如:

upstream app1  {
      server 127.0.0.1:3000; #App1's port
}

server {
    listen       *:80;
    server_name  app1.example.com;

    # You can put access_log / error_log sections here to break them out of the common log.

    ## send request to backend
    location / {
     proxy_pass              http://app1;
     proxy_set_header        Host            $host;
     proxy_set_header        X-Real-IP       $remote_addr;
     proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
   }
}

我更喜欢Nginx在Apache前面两个原因:1)nginx可以为静态文件提供更少的内存,以及2)nginx可以缓冲数据到客户端或从客户端发送数据,因此,互联网连接速度慢的人不会阻塞您的后端。

I prefer to have Nginx in front of Apache for two reasons: 1) nginx can serve static files with much less memory, and 2) nginx buffers data to/from the client, so people on slow internet connections don't clog your back-ends.

在测试配置时,请使用 nginx -s reload 重新加载配置,并使用 curl -v -H Host:app1 .example.com http:// localhost / 以从您的配置中测试特定域

When testing your config, use nginx -s reload to reload the config, and curl -v -H "Host: app1.example.com" http://localhost/ to test a specific domain from your config