Linux 设置nginx 以及java jar自启动

linux 设置nginx 自启动

sudo vim /etc/systemd/system/nginx.service
在文件中添加以下内容(根据你的JAR文件路径和用户需求进行调整)
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target
 
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
 
[Install]
WantedBy=multi-user.target

重新加载systemd,启用并启动你的服务:

sudo systemctl daemon-reload
sudo systemctl start nginx
sudo systemctl enable nginx

 

linux 设置java jar 自启动

 

在Linux系统中,要让Java的JAR文件自动启动,你可以通过几种方法来实现。以下是一些常见的方法:

1. 使用nohup和&

你可以在终端中使用nohup命令来运行你的JAR文件,并使用&将其置于后台运行。这样即使你关闭了终端,程序也会继续运行。

nohup java -jar your-application.jar &
2. 使用screen或tmux

screen或tmux是终端复用器,它们允许你启动一个或多个会话,并在这些会话中运行程序。即使你断开连接,会话也会继续运行。

首先,安装screen或tmux(如果尚未安装):

sudo apt-get install screen  # 对于Debian/Ubuntu
sudo yum install screen      # 对于CentOS/RHEL
sudo apt-get install tmux    # 对于Debian/Ubuntu
sudo yum install tmux        # 对于CentOS/RHEL
然后,使用以下命令启动一个新会话并运行你的JAR文件:

screen -S your-session-name -d -m java -jar your-application.jar
# 或者使用 tmux
tmux new -s your-session-name -d 'java -jar your-application.jar'
3. 使用systemd服务

对于更高级的自动启动和管理,你可以创建一个systemd服务。这样,你可以轻松地通过systemctl命令来启动、停止和管理你的服务。

创建一个新的服务文件:
sudo nano /etc/systemd/system/your-application.service
在文件中添加以下内容(根据你的JAR文件路径和用户需求进行调整):
[Unit]
Description=Your Java Application Service
After=network.target 
[Service]
User=your-user
ExecStart=/usr/bin/java -jar /path/to/your-application.jar
SuccessExitStatus=143
Restart=on-failure
Environment=JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64 
[Install]
WantedBy=multi-user.target

重新加载systemd,启用并启动你的服务:
sudo systemctl daemon-reload
sudo systemctl enable your-application.service
sudo systemctl start your-application.service

4. 使用cron定时任务

如果你希望在特定时间自动启动JAR文件,可以使用cron定时任务。
编辑cron任务:
crontab -e
添加一行来指定任务在特定时间运行,例如每天凌晨1点:
0 1 * * * /usr/bin/java -jar /path/to/your-application.jar > /path/to/logfile.log 2>&1
确保根据你的实际路径和需求调整这些命令。这些方法中的每一种都可以帮助你实现在Linux上自动启动Java JAR文件的需求。选择最适合你的场景的方法。

 

posted @ 2025-09-11 12:57  龙骑科技  阅读(11)  评论(0)    收藏  举报