1

Next.js 项目部署

 1 year ago
source link: https://www.jansora.com/notebook/144
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Next.js 项目部署Next.js 项目部署导航前往主站应用闲文杂记知识专栏代码在线代码魔方房价浅析小简助手

目录: Next.js 为您提供生产环境所需的所有功能以及最佳的开发体验:包括静态及服务器端融合渲染、 支持 TypeScript、智能化打包、 路由预取等功能 无需任何配置。

要部署一个 Next.js 项目,你可以选择多种托管平台。在这个例子中,我们将使用 Vercel,这是 Next.js 团队推荐的官方平台。当然,你也可以选择其他托管平台,例如 Netlify、Heroku 或自己的服务器。

如果你希望在自己的服务器上部署 Next.js 项目,可以按照以下步骤操作:

  1. 安装 Node.js

    首先,确保你的服务器已安装 Node.js。Next.js 需要 Node.js 运行环境。你可以在官方网站上找到适合你操作系统的安装说明:https://nodejs.org/en/download/

  2. 上传项目

    使用 SCP、SFTP 或者 Git 将 Next.js 项目上传到服务器的一个目录中。确保包含了所有的源代码和依赖文件(package.jsonyarn.lockpackage-lock.json)。

  3. 安装依赖

    yarn
    
  4. 构建项目

    yarn build
    
  5. 启动项目

    使用以下命令启动项目:

    yarn start
    

    默认情况下,Next.js 会在端口 3000 上运行。如果需要修改端口,请在启动命令后面添加 --port 参数,例如:

    yarn start --port 8080
    
  6. 设置反向代理(可选)

    如果你已经在服务器上运行了一个 Web 服务器(如 Nginx 或 Apache),你可能需要设置一个反向代理,将用户的请求从 Web 服务器代理到 Next.js 应用上。以下是一个 Nginx 示例配置:

    server {
        listen 80;
        server_name yourdomain.com;
    
        location / {
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    }
    

    yourdomain.com 替换为你的实际域名,并根据需要修改其他配置。

现在,你的 Next.js 项目应该已经在你的服务器上运行了。请注意,你可能需要配置防火墙规


  1. 部署到 systemd

systemd 是一个 Linux 系统和服务管理器,用于控制和管理系统启动过程。如果你想在 systemd 中指定一个目录,你可以在相应的服务单元文件中设置。这通常是在 /etc/systemd/system/ 目录下,或者在 /lib/systemd/system/ 目录下。

要指定目录,你需要编辑对应的服务单元文件,通常以 .service 结尾。下面是一个简单的示例,展示了如何在 systemd 服务单元文件中指定一个目录。

/etc/systemd/system/nextjs.service

[Unit]
Description=nextjs
Documentation=nextjs
After=network-online.target
Wants=network-online.target

[Service]
WorkingDirectory=/workspace/
Environment="PORT=30001"
EnvironmentFile=-/etc/default/%p
ExecStart=/usr/local/bin/next start
ExecStop=/bin/kill -HUP $MAINPID

KillSignal=SIGINT

[Install]
WantedBy=multi-user.target

要使更改生效,请运行以下命令重新加载 systemd 配置:

sudo systemctl daemon-reload

然后,根据需要启动、停止或重启你的服务:

sudo systemctl start nextjs.service
sudo systemctl stop nextjs.service
sudo systemctl restart nextjs.service

记得将 nextjs.service 替换为你的服务单元文件的名称。

  1. 部署到 vercel

https://vercel.com/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK