Mac上下载安装Vagrant、配置打包属于自己的开发环境(使用Homestead后续也会更新出来)

  • 为什么要使用Vagrant?

    • 保证PHP项目本地和服务器环境一致,避免出现一系列的问题。
  • 目前解决这种问题最佳的方法有Docker(生产环境line)、Vagrant(用于开发环境dev)。
  • Vagrant和Homestead的关系?

    • Homestead 是包含了Nginx Web服务器、PHP7、MySQL、Postgres、Redis、Memcached、Node,以及所有你在使用 Laravel 开发时需要用到的各种软件(Homestead Box 虚拟机盒子),它一套可配置的 Laravel 开发环境(Homestead 管理脚本),其实简单的说就是一个基于Laravel运行环境的打包的一个Box。
    • vagrant 是管理虚拟机的工具,主要作用是提供一个可配置、可移植和复用的软件环境。你也可以自己去安装配置一套自己的开发环境的打包可移植性Box。(例如类似于Homestead)。
    • VirtualBox 是虚拟机软件。
  • 重要提示:

    • homestead是基于vagrant的,vagrant是基于virtualBox的。也就是说,我们第一步需要下载virtualBox和vagrant两个软件。下载速度可能有点慢,尽量都使用最新版,如果两个软件版本相差太大,可能会导致homestead无法使用。
  • 官网下载地址:

  • 注意:推荐装Ubuntu 16.04.6 LTS 默认安装的php7.0

           vagrant@nz:~$ cat /etc/issue
           Ubuntu 16.04.6 LTS \n \l
           
           vagrant@nz:~$      php -v
           PHP 7.0.33-0ubuntu0.16.04.6 (cli) ( NTS )
           Copyright (c) 1997-2017 The PHP Group
           Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
               with Zend OPcache v7.0.33-0ubuntu0.16.04.6, Copyright (c) 1999-2017, by Zend Technologies
           vagrant@nz:~$
  • Vagrant 常用命令总结
        1. 显示当前版本 
            # vagrant --version  
        2. 列出所有Box
            # vagrant box list
        3. 添加一个Box
            # vagrant box add [options] <name, url, or path>
            3.1 可以从https://app.vagrantup.com/boxes/search下载各种Vagrant映像文件       
                # vagrant box add ubuntu/trusty64
            3.2 通过指定的URL添加远程box
                # vagrant box add https://atlas.hashicorp.com/ubuntu/boxes/trusty64
            3.3 添加一个本地box      
                # vagrant box add {box_name} {file_path}  
        4. 初始化一个新VM
           # vagrant init ubuntu/trustry64
        5. 启动一个VM
           # vagrant up
        6. 启用SSH登陆VM
           # vagrant ssh
        7. 查看VM当前的状态
           # vagrant status
        8. 关闭VM
            # vagrant halt
        9. 从box列表移除 
           # vagrant box remove [name]
        10. 重启虚拟机
           # vagrant reload
        11. 挂起虚拟机
           # vagrant suspend   
        12. 唤醒虚拟机
           # vagrant resume      
  • 目标

    • 成果是打包一个box镜像
    • 这个box镜像需要运行 LAMP(Linux + Apache + Mysql + PHP ) 和 LNMP( Linux + Nginx + Mysql + PHP)
      配置好3个比较流行的PHP框架运行环境

      • Yii2
      • Laravel5
      • ThinkPHP5
  • 基础环境

    • VirtualBox 6.0.12
    • Vagrant 2.2.5
    • 切记根据自己的操作系统下载,同时分32位和64位
    • Windows 额外工作

      • 可能需要配置环境变量
      • 安装Xshell命令行工具
      • 注意,一定要开启 VT-x/AMD-V 硬件加速
  • 启动虚拟机

                    zhengniu@zhengdeMBP:~/Downloads/study/vagrant$     mkdir -m 755 test         ------创建一个目录
                    zhengniu@zhengdeMBP:~/Downloads/study/vagrant$     ls
                    addCode  box      dev      shuoming test
                    zhengniu@zhengdeMBP:~/Downloads/study/vagrant$     vagrant box add ubuntu16046 ./box/ubuntu1606.box    -------添加一个box到Vagrant
                    ==> box: Box file was not detected as metadata. Adding it directly...
                    ==> box: Adding box 'ubuntu16046' (v0) for provider:
                        box: Unpacking necessary files from: file:///Users/zhengniu/Downloads/study/vagrant/box/ubuntu1606.box
                    ==> box: Successfully added box 'ubuntu16046' (v0) for 'virtualbox'!
                    zhengniu@zhengdeMBP:~/Downloads/study/vagrant$     cd test/
                    zhengniu@zhengdeMBP:~/Downloads/study/vagrant/test$     vagrant box list    -------查看添加的box
                    niuzheng    (virtualbox, 0)
                    ubuntu16046 (virtualbox, 0)        -----我们新添加的box
                    ubuntu1606  (virtualbox, 0)
                    zhengniu@zhengdeMBP:~/Downloads/study/vagrant/test$     vagrant init ubuntu16046     -------初始化添加的box
                     A `Vagrantfile` has been placed in this directory. You are now
                     ready to `vagrant up` your first virtual environment! Please read
                     the comments in the Vagrantfile as well as documentation on
                     `vagrantup.com` for more information on using Vagrant.
                   zhengniu@zhengdeMBP:~/Downloads/study/vagrant/test$     vagrant up                    -------启动虚拟机
                   Bringing machine 'default' up with 'virtualbox' provider...
                   ==> default: Importing base box 'ubuntu16046'...
                   ==> default: Matching MAC address for NAT networking...
                   ==> default: Setting the name of the VM: test_default_1569202782545_16096
                   ==> default: Clearing any previously set network interfaces...
                   ==> default: Preparing network interfaces based on configuration...
                       default: Adapter 1: nat
                   ==> default: Forwarding ports...
                       default: 22 (guest) => 2222 (host) (adapter 1)
                   ==> default: Running 'pre-boot' VM customizations...
                   ==> default: Booting VM...
                   ==> default: Waiting for machine to boot. This may take a few minutes...
                       default: SSH address: 127.0.0.1:2222
                       default: SSH username: vagrant
                       default: SSH auth method: private key
                       default: Warning: Connection reset. Retrying...
                       default:
                       default: Vagrant insecure key detected. Vagrant will automatically replace
                       default: this with a newly generated keypair for better security.
                       default:
                       default: Inserting generated public key within guest...
                       default: Removing insecure key from the guest if it's present...
                       default: Key inserted! Disconnecting and reconnecting using new SSH key...
                   ==> default: Machine booted and ready!
                   ==> default: Checking for guest additions in VM...
                       default: The guest additions on this VM do not match the installed version of
                       default: VirtualBox! In most cases this is fine, but in rare cases it can
                       default: prevent things such as shared folders from working properly. If you see
                       default: shared folder errors, please make sure the guest additions within the
                       default: virtual machine match the version of VirtualBox you have installed on
                       default: your host and reload your VM.
                       default:
                       default: Guest Additions Version: 5.1.38
                       default: VirtualBox Version: 6.0
                   ==> default: Mounting shared folders...
                       default: /vagrant => /Users/zhengniu/Downloads/study/vagrant/test

1.png

                   zhengniu@zhengdeMBP:~/Downloads/study/vagrant/test$     vagrant ssh       --------登入虚拟机
                   Welcome to Ubuntu 16.04.6 LTS (GNU/Linux 4.4.0-161-generic x86_64)
                   
                    * Documentation:  https://help.ubuntu.com
                    * Management:     https://landscape.canonical.com
                    * Support:        https://ubuntu.com/advantage
                   
                   0 packages can be updated.
                   0 updates are security updates.
                   
                   New release '18.04.2 LTS' available.
                   Run 'do-release-upgrade' to upgrade to it. 

3.png

  • L(A|N)MP

    • 安装Ngnix
            vagrant@ubuntu-xenial:~$ sudo apt-get update
            vagrant@ubuntu-xenial:~$ sudo apt-get install nginx
            vagrant@ubuntu-xenial:~$ nginx -v
            nginx version: nginx/1.10.3 (Ubuntu)
  • 测试Nginx
        vagrant@ubuntu-xenial:~$ curl -I 'http://127.0.0.1'
        HTTP/1.1 200 OK
        Server: nginx/1.10.3 (Ubuntu)
        Date: Mon, 23 Sep 2019 01:58:41 GMT
        Content-Type: text/html
        Content-Length: 612
        Last-Modified: Mon, 23 Sep 2019 01:50:58 GMT
        Connection: keep-alive
        ETag: "5d882502-264"
        Accept-Ranges: bytes
  • 安装Apache(测试访问,此时不能访问,因为80端口被nginx占用了,可以先把nginx停掉)
        vagrant@ubuntu-xenial:~$ sudo service nginx stop
        vagrant@ubuntu-xenial:~$ sudo apt-get install apache2
        vagrant@ubuntu-xenial:~$ apache2 -v
        Server version: Apache/2.4.18 (Ubuntu)
        Server built:   2019-09-16T13:13:53
        vagrant@ubuntu-xenial:~$ curl -I 'http://127.0.0.1'
        HTTP/1.1 200 OK
        Date: Mon, 23 Sep 2019 04:39:50 GMT
        Server: Apache/2.4.18 (Ubuntu)
        Content-Type: text/html; charset=UTF-8                   
  • 更改端口,将端口设置为8888,修改 ports.conf文件 (sudo vim /etc/apache2/ports.conf)
        vagrant@nz:/etc/apache2$ curl -I 'http://127.0.0.1:8888'
        HTTP/1.1 200 OK
        Date: Mon, 23 Sep 2019 04:39:50 GMT
        Server: Apache/2.4.18 (Ubuntu)
        Content-Type: text/html; charset=UTF-8
  • 安装Mysql
        vagrant@nz: sudo apt-get install mysql-server #服务器端,安装期间会提示输入为mysql设置root密码
        vagrant@nz: sudo apt-get install mysql-client #客户端
        vagrant@nz: mysql -uroot -p123456 #测试连接库,上面安装服务端没有设置密码,这里直接enter进入
  • 安装php
        vagrant@nz:sudo apt-get install php-cli
        vagrant@nz:/etc/apache2$ php -v
        PHP 7.0.33-0ubuntu0.16.04.6 (cli) ( NTS )
        Copyright (c) 1997-2017 The PHP Group
        Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
            with Zend OPcache v7.0.33-0ubuntu0.16.04.6, Copyright (c) 1999-2017, by Zend Technologies
  • PHP扩展
        sudo apt-get install php-mcrypt
        sudo apt-get install php-mysql
        sudo apt-get install php-gd
  • 支持apache2的php模块
        sudo apt-get install libapache2-mod-php7
  • 开启rewrite功能
        sudo a2enmod rewrite
  • 支持nginx fastcgi
        sudo apt-get install php-cgi php-fpm
  • 修改成9000端口 ,默认sock模式
        cd /etc/php/7.0/fpm/pool.d
        sudo vim www.conf # search listen = 127.0.0.1:9000
        sudo /etc/init.d/php7.0-fpm restart

Vagrant高级配置(修改Vagrantfile文件)

  • 端口转发配置
        config.vm.network "forwarded_port", guest: 80, host: 8888 
        config.vm.network "forwarded_port", guest: 8888, host: 8889
        config.vm.network "private_network", ip: "192.168.33.10"
        config.vm.synced_folder "/Users/zhengniu/Downloads/study/vagrant/dev/code", "/var/www"

框架配置

  • 分别下载tp5、yii2、laravel5.5 我这里只说明了全局安装,局部安装请自行百度,so easy。
    composer self-update     ----更新composer
    composer config -g repo.packagist composer https://packagist.phpcomposer.com    ---- 切换源  
    composer create-project topthink/think=5.0.* tp5  --prefer-dist                 ---- 下载tp5
    composer create-project --prefer-dist yiisoft/yii2-app-basic yii2               ---- 下载yii2
    composer create-project --prefer-dist laravel/laravel laravel5 "5.5.*"          ---- 下载laravel (PHP >= 7.0.0请注意laravel运行环境,后期会写出Homestead的教学)
  • 注意事项

    • tp5 runtime目录有可写权限
    • yii2 runtime、web/assets目录有可写权限
    • laravel5 storage和bootstrap/cache目录有可写权限
  • 配置apache2

    • tp5
        vagrant@nz: cd /etc/apache2/sites-enabled
        vagrant@nz: ls
        000-default.conf
        vagrant@nz: sudo vim tp5.conf
        <VirtualHost *:8888>
                ServerName tp5.vagrant.com
                DocumentRoot /var/www/tp5/public
                ErrorLog ${APACHE_LOG_DIR}/error.log
                CustomLog ${APACHE_LOG_DIR}/access.log combined
        </VirtualHost>
  • yii2
        vagrant@nz: sudo vim yii2.conf
        <VirtualHost *:8888>
                ServerName yii2.vagrant.com
                DocumentRoot /var/www/yii2/web
                ErrorLog ${APACHE_LOG_DIR}/error.log
                CustomLog ${APACHE_LOG_DIR}/access.log combined
        </VirtualHost>
  • laravel5
      vagrant@nz: sudo vim laravel.conf
      <VirtualHost *:8888>
              ServerName laravel.vagrant.com
              DocumentRoot /var/www/laravel5/public
              ErrorLog ${APACHE_LOG_DIR}/error.log
              CustomLog ${APACHE_LOG_DIR}/access.log combined
      </VirtualHost>  
  • Forbidden解决办法
      cd /etc/apache2
      sudo vim apache2.conf
    
      <Directory /var/www/>
             Options FollowSymLinks
             AllowOverride ALL # 打开rewrite
             #Require all granted
      </Directory>
  • 配置nginx

    • tp5
      vagrant@nz: cd /etc/nginx/conf.d
      vagrant@nz:/etc/nginx/conf.d$ ls
      vagrant@nz: sudo vim tp5.conf
      server {
              charset utf-8;
              client_max_body_size 128M;
              listen 80;
              server_name tp5.vagrant.com;
              root  /var/www/tp5/public;
              index  index.html index.htm index.php;
              #解决跨域问题
              location ~* \.(eot|otf|ttf|woff)$ {
                  add_header Access-Control-Allow-Origin *;
              }
              location / {
                  index    index.html index.php;
                  if ( -f $request_filename) {
                      break;
                  }
                  if ( !-e $request_filename) {
                      rewrite ^/(.*)$ /index.php/$1 last;
                      break;
                  }
              }
      
              location ~ \.php {
                  set $script $uri;
                  set $path_info "";
                  if ($uri ~ "^(.+\.php)(/.+)") {
                      set $script $1;
                      set $path_info $2;
                  }
                  include   fastcgi_params;
                  fastcgi_index    index.php?IF_REWRITE=1;
                  fastcgi_pass   127.0.0.1:9000;
                  fastcgi_param    PATH_INFO    $path_info;
                  fastcgi_param    SCRIPT_FILENAME    $document_root$fastcgi_script_name;
                  fastcgi_param    SCRIPT_NAME    $script;
                  try_files $uri =404;
              }
      
          }
  • yii2
        vagrant@nz: sudo vim yii2.conf
        server {
                charset utf-8;
                client_max_body_size 128M;
                listen 80;
                server_name yii2.vagrant.com;
        
                root  /var/www/yii2/web;
                index  index.php;
        
                location ~* \.(eot|otf|ttf|woff)$ {
                    add_header Access-Control-Allow-Origin *;
                }
        
                location / {
                    try_files $uri $uri/ /index.php?$args;
                }
        
                location ~ \.php$ {
                    include   fastcgi_params;
                    fastcgi_pass   127.0.0.1:9000;
                    try_files $uri =404;
                }
        
            }
  • laravel5
        vagrant@nz: sudo vim laravel.conf
        server {
                charset utf-8;
                client_max_body_size 128M;
                listen 80;
                server_name laravel.vagrant.com;
        
                root  /var/www/laravel5/public;
                index  index.php;
        
                location ~* \.(eot|otf|ttf|woff)$ {
                    add_header Access-Control-Allow-Origin *;
                }
        
                location / {
                    try_files $uri $uri/ /index.php?$args;
                }
        
                location ~ \.php$ {
                    include   fastcgi_params;
                    fastcgi_pass   127.0.0.1:9000;
                    try_files $uri =404;
                }
        
            }
  • 在主机的hosts中配置
   sudo vim /ect/hosts
   192.168.33.10 tp5.vagrant.com yii2.vagrant.com laravel.vagrant.com
  • 访问
    5.png

6.png

7.png

8.png

9.png

10.png

优化

  • 虚拟机主机名
    config.vm.hostname = "nz"
  • 配置虚拟机内存和CPU、虚拟机名称
       config.vm.provider "virtualbox" do |vb|
         #   # Display the VirtualBox GUI when booting the machine
         #   vb.gui = true
         #
         #   # Customize the amount of memory on the VM:
         #   vb.memory = "1024"
             vb.name = "ubuntu_1606"
             vb.memory = "1024"
             vb.cpus = 2
         end
  • nginx注意事项
    2.png
  • 打包命令
     vagrant package --output xxx.box

1111.png

  • 升级问题(修改Vagrantfile文件,找到以下内容,这里以redis为例子演示)
    config.vm.provision "shell", inline: <<-SHELL
      #   apt-get update
      #   apt-get install -y apache2
          apt-get install -y redis-server
      SHELL
  • 然后vagrant reload --provision 重启
    安装redis.png

注意:

  • 一定要正常关闭虚拟机,进入初始化虚拟机的目录,不然下次开机有可能引起异常错误。
     vagrant halt
  • 如果执行vagrant up 出现卡死(请修改Vagrantfile文件,打开vb.gui = true 查看调试)

关注友儿不迷路

Last modification:September 24th, 2019 at 08:16 pm
如果觉得我的文章对你有用,请随意赞赏