1. 程式人生 > >nginx和tomcat共同使用80埠(通過反向代理實現)

nginx和tomcat共同使用80埠(通過反向代理實現)

在伺服器搭起nginx後發現,nginx使用的預設為80埠,而前不久剛剛把自己的tomcat配置改為80埠並繫結域名,所以造成了nginx無法啟動的情況,具體報錯資訊為

nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)

想到給域名後面加上埠號並不合理,於是採用了nginx反向代理來解決這一問題,具體解決方案如下:
1.首先將tomcat改為8080埠(具體細節不再闡述,可自行百度)
2.在nginx的安裝目錄下 (我的目錄是 /usr/local/nginx )建立一個新的資料夾 vhosts,然後在vhosts資料夾下建立一個tomcats.conf檔案
tomcats.conf檔案內容如下:

server {
        listen       80;
        server_name  xx.xx.xx.xx;(想要設定的訪問地址)
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
             proxy_pass http://xx.xx.xxx.xxx:8080;(現在想要設定的路徑的訪問地址)
             root   html;
             index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}

3.開啟nginx安裝目錄下的conf下的nginx.conf檔案
4.在檔案底部加上

include /usr/local/nginx/vhosts/*;     (包含所有虛擬機器主機檔案,加在最後那個大括號前面)

5.然後在檔案中間找到

        location / {
            proxy_pass    http://xx.xx.xxx.xxx:8080;     (加上這個,指定自己本機的tomcat的地址)
            root   html;
            index  index.html index.htm;
        }

重啟tomcat,nginx

另外補上一點,其實nginx一般是不用重啟的,它可以通過與-s引數呼叫可執行來控制

nginx -s signal

其中,訊號可以是下列之一:

stop — fast shutdown
quit — graceful shutdown
reload — reloading the configuration file
reopen — reopening the log files

在配置檔案中所作的更改不會被應用,直到命令重新配置被髮送到nginx的或重新啟動。要重新載入配置,執行:

nginx -s reload

如果非要重新啟動或停止,可採用下面的方法
從容停止
 1、檢視程序號

ps -ef|grep nginx

2、殺死程序,注意一共有三個程序,一定要殺死後面帶master的程序id

kill -QUIT xxxx

快速停止
1、檢視程序號

 ps -ef|grep nginx

2、殺死程序

 kill -TERM 2132

 kill -INT 2132

強制停止

pkill -9 nginx

在操作過程中遇到一個坑:
配置nginx 反向代理的時候出現了

nginx: [emerg] invalid URL prefix in /usr/local/nginx/conf/nginx.conf 

這個錯誤,意思是nginx配置的URL地址字首不正確,後來重新看了下,發現的確是字首沒有寫好,正確寫法如下:
在這裡插入圖片描述
然後重啟nginx服務,發現一切符合正常情況。