解決在Ubuntu Server 22.04安裝NGINX失敗

解決在Ubuntu Server 22.04安裝NGINX(nginx.org)失敗

第一次在 Ubuntu Server 22.04 安裝 NGINX,參考官方教學與另一篇都覺得寫的不錯,反正就是 apt install nginx 就結束了。看到應該這裡就知道,事情沒那麼簡單,因為參考了一些文件,安裝的都不是很順利,因此記下此筆記一篇。

官方教學與另一篇我覺得都寫的不錯:

但執行起來怎麼問題一堆:

$ sudo apt install nginx
# 省略
Setting up nginx-core (1.18.0-6ubuntu14.7) ...
Job for nginx.service failed because the control process exited with error code.
See "systemctl status nginx.service" and "journalctl -xeu nginx.service" for details.
invoke-rc.d: initscript nginx, action "start" failed.
× nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Thu 2025-09-04 06:06:04 UTC; 6ms ago
       Docs: man:nginx(8)
    Process: 1695 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=1/FAILURE)
        CPU: 9ms

Sep 04 06:06:04 kklabs systemd[1]: Starting A high performance web server and a reverse proxy server...
Sep 04 06:06:04 kklabs nginx[1695]: nginx: [emerg] socket() [::]:80 failed (97: Unknown error)
Sep 04 06:06:04 kklabs nginx[1695]: nginx: configuration file /etc/nginx/nginx.conf test failed
Sep 04 06:06:04 kklabs systemd[1]: nginx.service: Control process exited, code=exited, status=1/FAILURE
Sep 04 06:06:04 kklabs systemd[1]: nginx.service: Failed with result 'exit-code'.
Sep 04 06:06:04 kklabs systemd[1]: Failed to start A high performance web server and a reverse proxy server.
dpkg: error processing package nginx-core (--configure):
 installed nginx-core package post-installation script subprocess returned error exit status 1
dpkg: dependency problems prevent configuration of nginx:
 nginx depends on nginx-core (<< 1.18.0-6ubuntu14.7.1~) | nginx-full (<< 1.18.0-6ubuntu14.7.1~) | nginx-light (<< 1.18.0-6ubuntu14.7.1~) | nginx-extras (<< 1.18.0-6ubuntu14.7.1~); however:
  Package nginx-core is not configured yet.
  Package nginx-full is not installed.
  Package nginx-light is not installed.
  Package nginx-extras is not installed.
 nginx depends on nginx-core (>= 1.18.0-6ubuntu14.7) | nginx-full (>= 1.18.0-6ubuntu14.7) | nginx-light (>= 1.18.0-6ubuntu14.7) | nginx-extras (>= 1.18.0-6ubuntu14.7); however:
  Package nginx-core is not configured yet.
  Package nginx-full is not installed.
  Package nginx-light is not installed.
  Package nginx-extras is not installed.

dpkg: error processing package nginx (--configure):
 dependency problems - leaving unconfigured
Processing triggers for ufw (0.36.1-4ubuntu0.1) ...
No apport report written because the error message indicates its a followup error from a previous failure.
                                                                                                          Processing triggers for man-db (2.10.2-1) ...
Processing triggers for libc-bin (2.35-0ubuntu3.10) ...
Errors were encountered while processing:
 nginx-core
 nginx
needrestart is being skipped since dpkg has failed
E: Sub-process /usr/bin/dpkg returned an error code (1)

上面錯誤實在看不出那裡有錯。參考網路上的解決方案,檢查 80 Port 是否被佔用,或重裝與換主機重裝數十次,還是一樣的錯誤:

# 確定 Port
$ sudo ss -tuln
Netid              State               Recv-Q              Send-Q                             Local Address:Port                             Peer Address:Port              Process
udp                UNCONN              0                   0                                  127.0.0.53%lo:53                                    0.0.0.0:*
tcp                LISTEN              0                   4096                               127.0.0.53%lo:53                                    0.0.0.0:*
tcp                LISTEN              0                   128                                      0.0.0.0:22                                    0.0.0.0:*
  
# 移除重裝
$ sudo apt purge nginx*
$ sudo apt-get autoclean && sudo apt-get autoremove
$ sudo apt-get install nginx*
$ sudo dpkg --configure -a

後來覺得會不會是 nginx.conf 有問題:

$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: [emerg] socket() [::]:80 failed (97: Unknown error)
nginx: configuration file /etc/nginx/nginx.conf test failed

呀!呀!呀!預設定 nginx.conf 還真的有問題,我暈了!其實類似的日誌,前面也有,有時真的很多,沒注意到:

Sep 04 06:06:04 kklabs nginx[1695]: nginx: [emerg] socket() [::]:80 failed (97: Unknown error)
Sep 04 06:06:04 kklabs nginx[1695]: nginx: configuration file /etc/nginx/nginx.conf test failed

查詢 /etc/nginx/nginx.conf 的內容:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}


#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
#
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

本想改 nginx.conf 來修正,但越想越怪。為什麼會給一個預設壞掉的 nginx.conf。而且看著它安裝的套件內容(被省略了),不像平常從 https://nginx.org 下載來安裝的版本,比較像是商業版。從 nginx: Linux packages 能找到目前開源版本的安裝方式(請以官方文件為主,我就不複製過來了)。

$ sudo apt install nginx
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following NEW packages will be installed:
  nginx
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 1,169 kB of archives.
After this operation, 3,797 kB of additional disk space will be used.
Get:1 http://nginx.org/packages/ubuntu jammy/nginx amd64 nginx amd64 1.28.0-1~jammy [1,169 kB]
Fetched 1,169 kB in 3s (352 kB/s)
Selecting previously unselected package nginx.
(Reading database ... 110537 files and directories currently installed.)
Preparing to unpack .../nginx_1.28.0-1~jammy_amd64.deb ...
Unpacking nginx (1.28.0-1~jammy) ...
Setting up nginx (1.28.0-1~jammy) ...
/var/lib/dpkg/info/nginx.postinst: 27: kill: Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or
kill -l [exitstatus]
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /lib/systemd/system/nginx.service.
Processing triggers for man-db (2.10.2-1) ...

NGINX 安裝來源沒問題了,但 nginx.service 還是沒能順利啟動:

$ systemctl status nginx.service
× nginx.service - nginx - high performance web server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Thu 2025-09-04 14:06:04 CST; 2h 20min ago
       Docs: https://nginx.org/en/docs/
        CPU: 9ms

一樣測一下與看一下 nginx.conf

$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

$ cat /etc/nginx/nginx.conf

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

習慣 Windows 版本看這份 nginx.conf 不是很習慣,它應該是把沒必要的組態都採用預設值(等於是最小化組態檔),重點是測試是通過的。那就讓我們手動啟用 nginx.service 試試看:

$ systemctl start nginx.service
# 權限身分
$ systemctl status nginx.service
● nginx.service - nginx - high performance web server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Thu 2025-09-04 16:34:39 CST; 14s ago
       Docs: https://nginx.org/en/docs/
    Process: 4245 ExecStart=/usr/sbin/nginx -c ${CONFFILE} (code=exited, status=0/SUCCESS)
   Main PID: 4246 (nginx)
      Tasks: 3 (limit: 9345)
     Memory: 3.3M
        CPU: 8ms
     CGroup: /system.slice/nginx.service
             ├─4246 "nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf"
             ├─4247 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""
             └─4248 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""

NGINX 啟動成功了,快來試試:

$ curl http://localhost
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

HTTP 存取 NGINX 成功了!再看一眼 Port 的狀態,也確定繫結到 80 Port。

$ sudo ss -tuln
Netid              State               Recv-Q              Send-Q                             Local Address:Port                             Peer Address:Port              Process
tcp                LISTEN              0                   511                                      0.0.0.0:80                                    0.0.0.0:*

目前看起來的問題在於,網路上(疑,我也網路上)的教學可能都是 NGIXN 還沒被 F5 買去之前寫的。現在 apt install nginx 預設情況下安裝的是商業版,但商業版為何會一開始就給一個壞掉的 nginx.conf,這我就沒頭緒了。不過還好,因為一直錯才發現問題,才會去設定開源版的 NGINX,改為開源版的 NGINX 安裝,除了要手動啟動外,一切就都很順利的運作中。

沒有留言:

張貼留言

感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。