Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 快速查看埠佔用並終止進程:netstat + kill 實戰

編輯:Linux 教學

部署服務時常遇到「Address already in use」錯誤,需快速定位佔用埠的進程並釋放。以下為最常用的 netstat / ss + kill 組合拳。

查看指定埠佔用情況

# 以埠 8083 為例
netstat -apn | grep 8083
# 輸出範例:
# tcp  0  0 192.168.2.17:8083  0.0.0.0:*  LISTEN  3877/java

參數說明:-a 所有連線、-p 顯示 PID/程式名(需 root)、-n 數值格式顯示 IP/埠。

現代替代工具:ss(更快、iproute2 套件)

ss -ltnp | grep 8083
# -l 監聽、-t TCP、-n 數值、-p 進程

終止進程

kill -9 3877   # 強制殺死 PID 3877

優雅關閉建議:先嘗試 kill 3877(SIGTERM),讓程式釋放資源、刷新日誌;5 秒後仍存活再用 kill -9(SIGKILL)。

一鍵腳本:自動殺死指定埠進程

#!/bin/bash
# kill_port.sh 
PORT=${1:-8080}
PID=$(ss -ltnp "sport = :$PORT" | awk 'NR>1 {print $NF}' | cut -d= -f2 | cut -d, -f1)
if [ -n "$PID" ]; then
    echo "Killing PID $PID on port $PORT"
    kill -9 "$PID"
else
    echo "Port $PORT is free"
fi

用法:./kill_port.sh 8083

常見埠衝突場景與對策

Copyright © Windows教程網 All Rights Reserved
場景對策
舊進程未正常退出(TIME_WAIT)等待 60 秒或調整 net.ipv4.tcp_tw_reuse=1
多實例搶佔同一埠修改配置檔 port 參數,錯開埠號
系統服務佔用(如 80/443)停用預設服務 systemctl disable --now httpd