手动部署 Laravel 应用

手动部署 Laravel 应用(基于Ubuntu18.04)

0. 腾讯云服务器需要注意

  1. 禁用systemd-resolved服务
$ systemctl stop systemd-resolved
$ systemctl disable systemd-resolved
  1. 编辑/etc/resolv.conf文件,默认是127.0.0.53
$ nameserver 127.0.0.53            # 原始
$ nameserver 114.114.114.114    # 替换后
  1. 注意/etc/apt/source.list中的源地址
    mirrors.tencentyun.com替换成mirrors.cloud.tencent.com,否则镜像有问题

1. 初始化系统

  1. 更新软件源
$ apt update
  1. 查看可升级软件包,并升级(生产环境谨慎操作)
$ apt list --upgradable
$ apt upgrade
  1. 本地化配置(国内服务器都已经配置好)
$ locale-gen en_US.UTF-8
$ update-locale LC_ALL=en_US.UTF-8
$ timedatectl set-timezone Asia/Shanghai

2. 安装 Nginx

  1. 安装 Nginx
$ apt install nginx
  1. 管理 Nginx 服务
$ service nginx start        # 启动 Nginx
$ service nginx stop        # 停止 Nginx
$ service nginx restart        # 重启 Nginx

$ systemctl enable nginx    # 启用 Nginx 开机启动
$ systemctl disable nginx     # 禁用 Nginx 开机启动
  1. 确认 Nginx 正常运行

在浏览器内输入服务器公网 IP(或域名)并打开,出现欢迎界面说明 Nginx 安装成功

3. 安装 PHP-FPM

  1. 配置第三方软件源
$ apt install -y software-properties-common
$ add-apt-repository -y ppa:ondrej/php
$ apt-get update
  1. 安装 PHP

PHP 的安装分为三个软件包:PHP、PHP-CLI、PHP-FPM

$ apt install -y php7.2 php7.2-cli php7.2-fpm
  1. 安装 PHP 必要的扩展
$ apt install -y php7.2-mbstring php7.2-xml php7.2-bcmath php7.2-curl php7.2-gd php7.2-mysql php7.2-opcache php7.2-zip php7.2-sqlite3 php7.2-json
  1. 根据命令搜索当前软件源内包
$ apt-cache search php7.2
  1. 管理 PHP-FPM 服务
$ service php7.2-fpm restart    # 重启 PHP-FPM
$ service php7.2-fpm start        # 启动 PHP-FPM
$ service php7.2-fpm stop        # 停止 PHP-FPM

$ systemctl enable php7.2-fpm    # 启用 PHP-FPM 开机启动
$ systemctl disable php7.2-fpm    # 禁用 PHP-FPM 开机启动
  1. 确认 PHP-FPM 正常运行
$ ps aux | grep php

如果 PHP-FPM 进程不存在,则只有 grep 进程

4. 安装 Git 和 Composer

  1. 安装 Git
$ apt install -y git
  1. 安装 Composer
$ wget https://raw.githubusercontent.com/composer/getcomposer.org/master/web/installer -O - -q | php -- --filename=composer -- install-dir=/usr/local/bin
  1. composer 执行权限问题(新建普通用户,防止composer包有恶意代码)
$ composer -V
Do not run Composer as root/super user!
  1. 配置 Packagist 中国镜像
$ composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

5. 安全加固,避免使用根目录用户

  1. 创建新用户

在创建新用户前先创建用户组,例如foodaily

$ addgroup foodailycompany

随后创建新用户,例如foodaily

$ useradd -d /home/foodaily -s /bin/bash -m foodaily

接着将用户添加至用户组:

$ usermod -a -G foodailycompany -G www-data foodaily

最后为新用户设置密码:

$ passwd foodaily
$ Enter new UNIX password:<输入密码>
$ Retype new UNIX password:<再次输入密码>

切换到新用户下面

$ su foodaily

切换回 root 用户

$ su root
  1. 测试效果

断开 SSH 链接,在本地使用以下命令作为foodaily用户登录到服务器

$ ssh foodaily@公网IP
$ foodaily@公网IP's password:<输入密码>
  1. 禁止根用户 SSH 登录
$ sed -i -E 's/#?\s*(PermitRootLogin)(.*)$/\1 no/' /etc/ssh/sshd_config

建议手动编辑 /etc/ssh/sshd_config 文件,搜索PermitRootLogin这一关键字,将整行改成PermitRootLogin no,确保正行修改,首尾无多余字符
随后重启 SSH 服务即可

$ service ssh restart
  1. 再次测试效果
$ ssh root@公网IP
$ Permission denied, please try again.

注意 :如果要使用root用户,需要先通过foodaily用户 SSH 登录服务器,然后再通过su root 来切换 root 用户

6. 部署应用代码

  1. 使用 Git 拉取项目(HTTPS 协议)
$ cd /var/www/
$ git clone https://github.com/username/demo.git demo
$ Username for 'https://github.com': <输入你的用户名>
$ Password for 'https://example@github.com': <请输入你的密码>

私有项目需要输入账号和密码

  1. 使用 Composer 安装依赖
$ cd demo
$ composer install

提示找不到unzip扩展

$ apt install unzip
  1. 使用 Npm 或者 Yarn 安装依赖
$ cd demo
$ sudo npm/yarn install
  1. 配置环境变量

依赖安装完成后,需要将.env.example文件复制为.env文件,并生成APP_KEY秘钥:

$ cd /var/www/demo
$ php -r "file_exists('.env') || copy('.env.example', '.env');"
$ php artisan key:generate --ansi
  1. 配置文件所有者
$ chown -R www-data:www-data .

7. 配置 Nginx 站点

  1. /etc/nginx/sites-enabled文件夹下放置每个网站的conf
$ foodaily.conf
  1. 现成 Nginx 配置如下:
server {
    listen 80;
    server_name 公网IP或域名;     # 此为必修改项,请替换为服务器公网 IP 或域名
    root /var/www/demo/public; # 此为必修改项,请注意指向站点根目录的 public 子目录

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; # 请注意核对 PHP 版本
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

通常仅需要修改 server_namerootfastcgi_pass三个选项即可

  1. 重载 Nginx(三者等价)
$ service nginx restart
$ service nginx reload
$ nginx -s reload
  1. Nginx https配置
server {
    listen 443 ssl;
    ssl_certificate /usr/local/nginx/ssl/server.crt;
    ssl_certificate_key    /usr/local/nginx/ssl/server.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!MD5:!DH;

    server_name 公网IP或域名;     # 此为必修改项,请替换为服务器公网 IP 或域名
    server_name foodaily.com www.foodaily.com;    # 如果有www的要填写两个
    root /var/www/demo/public; # 此为必修改项,请注意指向站点根目录的 public 子目录

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; # 请注意核对 PHP 版本
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
# 全站使用 HTTPS,让通过 HTTP 访问的用户301跳转到 HTTPS
server {
    listen    80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

8. 安装 MySQL 5.7

  1. 安装 MySQL
$ sudo apt install mysql-server
  1. 配置 MySQL
$ sudo mysql_secure_installation

在成功设置 root 密码后还有一些列的安全设置

  1. 安全设置
$ Do you wish to continue with the password provided?([Y/n]): y
$ Enter current password for root (enter for none): <输入密码>
$ Change the root password? [Y/n] n
$ Remove anonymous users? [Y/n] y
$ Disallow root login remotely? [Y/n] n
$ Remove test database and access to it? [Y/n] n
$ Reload privilege tables now? [Y/n] y
  1. 添加用户
$ create user usernamexxx identified by 'passwordxxx';

用户名:usernamexxx,密码:passwordxxx

  1. 授权
$ grant all privileges on db_name.* to usernamexxx@'%' identified by 'passwordxxx';
$ flush privileges;

给用户usernamexxx赋予db_name数据库的所有表的所有权限

  1. 修改密码
$ update mysql.user set password = password('passwordxxx') where user = 'usernamexxx' and host = '%';
$ flush privileges;
  1. 删除用户(会删除用户以及对应的权限,mysql.user和mysql.db表的相应记录随之删除)
$ drop user usernamexxx@'%';
  1. 使用MySQL
$ /etc/init.d/mysql start
$ /etc/init.d/mysql stop
$ /etc/init.d/mysql restart
  1. MySQL密码含有特殊字符的话,在.env文件中要加上双引号,否则密码无法完全识别

9. 生产环境的必要优化

  1. Nginx 配置
server {
    location ~* \.(js|css)$ {
        expires 24h;
    }
}
  1. Laravel 的配置缓存
$ php artisan config:cache        # 生成配置缓存

注意 :当开启配置缓存后,env()函数将会失效,它永远返回null,因此务必确保在非config目录下使用env函数。生成缓存后,对配置的修改将不会生效,需要执行下面命令清除它们

$ php artisan config:clear        # 清除配置缓存
  1. Laravel 的路由缓存
$ php artisan route:cache        # 生成路由缓存

注意:若路由注册存在闭包,则无法使用该功能,生成缓存后,对路由的修改将不会生效,需要执行下面命令清除它们

$ php artisan route:clear        # 清除路由缓存

注意:别直接使用下面命令清除所有缓存,因为有可能会清除掉 Redis 缓存

$ php artisan cache:clear
  1. Composer (安装依赖时)
$ composer install --optimize-autoloader --no-dev

其中--optimize-autoloader表示生成优化后的自动加载器,--no-dev表示不安装composer.json中require-dev声明的扩展包

  1. 文件权限

文件权限应当遵守『最小权限原则』,即权限越小越好。

$ chmod -R 750 /var/www/demo
  1. 杂项
$ php artisan storage:link        # 软链接,storage/app/public 到 public 目录
$ php artisan migrate            # 执行迁移
$ php artisan db:seed            # 执行数据填充

欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 ljheiseberg@163.com

文章标题:手动部署 Laravel 应用

文章字数:2.1k

本文作者:LJHeisenberg

发布时间:2019-11-20, 12:30:44

最后更新:2021-04-27, 10:55:50

原始链接:https://ljheisenberg1072.github.io/2019/11/20/deploy-laravel-project-byhands/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录