laradock配置啓動,開發使用

一、起源

a.從安裝開始瞭解

後盾人: LaraDock 新手使用教程php

b.官方文檔

laradock 中文文檔
碼雲:Laradockhtml

二、環境構建

說明:本機原有少部分端口已經佔用,按端口+10000對外端口配置。node

a.docker-composer安裝

wget -O docker-compose "https://github.com/docker/compose/releases/download/1.26.0-rc4/docker-compose-Linux-x86_64"
mv docker-compose /usr/local/bin/docker-compose
chown cffycls:docker /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose

b.環境構建

修改 .env 的php、MySQL版本
### 後盾人文檔搭建的目錄結構(可直接laravel new 2個)
hdcms
houdunren
laradock *[該文件夾爲下面的根操做路徑]
###
docker-compose up -d nginx php-fpm mysql workspace
漫長...

workspace很卡,換源fix,重試:mysql

### curl: (7) Failed to connect to raw.githubusercontent.com port 443: Connection refused
1) 百度上面: https://www.jianshu.com/p/c2e829027b0a
cat /etc/hosts && echo -e "#githubusercontent\n199.232.68.133  githubusercontent.com\n">>/etc/hosts
再次執行依舊報錯
2) 依據錯誤狀況,備份並修改 workplace/Dockerfile:
【這裏採用本地下載,修改Dockerfile手動添加文件】 
### 解決:
wget -O workplace/install.sh https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh
# workplace/Dockerfile 修改
添加
COPY --chown=laradock:laradock ./install.sh /work_install.sh
修改
    #curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash \
    ls $NVM_DIR -alh && ls -alh /work_install.sh && id && /work_install.sh \

workspace插件比較多。nginx

nodejs、github換源:
## workplace/Dockerfile 修改
添加
echo -e "\n151.101.185.194  github.global-ssl.fastly.net \n192.30.253.112 github.com\n" >> /etc/hosts \
## .env 修改:
WORKSPACE_COMPOSER_REPO_PACKAGIST=https://mirrors.aliyun.com/composer/
WORKSPACE_NVM_NODEJS_ORG_MIRROR=https://npm.taobao.org/mirrors/node
WORKSPACE_NPM_REGISTRY=https://registry.npm.taobao.org
.env衝突端口修改
### 自定義端口映射,使用域名訪問、不加端口時,須要配合本機80反向代理
HTTP_PORT=80\n ==> HTTP_PORT=10080\n phpmyadmin
HTTP_PORT=8080\n ==> HTTP_PORT=18080\n nginx
HTTPS_PORT=443\n ==> HTTPS_PORT=10443\n nginx
VARNISH_BACKEND_PORT=81 ==> VARNISH_BACKEND_PORT=10081 nginx
PORT==3306\n ==> PORT=1=3306\n mysql
PORT=6379\n ==> PORT=16379\n redis
docker system prune 清理緩存嘗試

c. 構建結果

### docker-compose ps

laradock_docker-in-docker_1   dockerd-entrypoint.sh            Up      2375/tcp, 2376/tcp                                                                                                   
laradock_mysql_1              docker-entrypoint.sh mysqld      Up      0.0.0.0:13306->3306/tcp, 33060/tcp                                                                                   
laradock_nginx_1              /bin/bash /opt/startup.sh        Up      0.0.0.0:10443->443/tcp, 0.0.0.0:10080->80/tcp, 0.0.0.0:10081->81/tcp                                                 
laradock_php-fpm_1            docker-php-entrypoint php-fpm    Up      9000/tcp                                                                                                             
laradock_phpmyadmin_1         /docker-entrypoint.sh apac ...   Up      0.0.0.0:18081->80/tcp                                                                                                
laradock_redis_1              docker-entrypoint.sh redis ...   Up      0.0.0.0:16379->6379/tcp                                                                                              
laradock_workspace_1          /sbin/my_init                    Up      0.0.0.0:2222->22/tcp, 0.0.0.0:3000->3000/tcp, 0.0.0.0:3001->3001/tcp, 0.0.0.0:8001->8000/tcp, 0.0.0.0:18080->8080/tcp

三、使用測試

a.打開 phpmyadmin

http://127.0.0.1:18081/    laradock_phpmyadmin    OK
#登陸 find / -name '*.conf' |xargs grep -rn ServerName
### php_network_getaddresses: getaddrinfo failed: Name or service not known
Dockerfile:
sed -i "s/\$cfg\['Servers'\]\[\$i\]\['host'\] = 'localhost';/\$cfg\['Servers'\]\[\$i\]\['host'\] = '127.0.0.1';/"  /var/www/html/config.sample.inc.php
echo "ServerName localhost:80" >> /etc/apache2/sites-enabled/000-default.conf
#echo "ServerName 127.0.0.1:80" >> /etc/apache2/sites-enabled/000-default.conf

docker-compose build phpmyadmin
登陸
### Failed to set session cookie. Maybe you are using HTTP instead of HTTPS to access phpMyAdmin.
host: mysql
root: root
password: root

phpmyadmin建表操做正常。laravel

b.打開 項目初始頁面

項目數據庫配置git

### hdcms/.env [注意]這裏使用容器名稱的端口是`內部`端口3306-6379
DB_HOST=mysql
DB_HOST=redis

#### laradock/nginx/sites/xx.conf 
server_name houdunren.test;
root /var/www/hdcms/public;

docker-compose restart nginx

注意配置hosts時端口設置會無效github

### deepin開發主機操做
#添加hosts,準備瀏覽測試(這裏127.0.0.1:10080端口自動忽略)
cat >> /etc/hosts <<EOF
127.0.0.1  hdcms.test
127.0.0.1  houdunren.test
EOF
cat /etc/hosts
配置Nginx轉發代理:
server {
        listen 80;
        server_name  *.test *.api;
        location / {
            #本地開發時,使用主機名稱訪問的 80的nginx轉發到docker的10080nginx 
            proxy_set_header Host               $host;
            proxy_set_header X-Real-IP          $remote_addr;
            proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto  $scheme;
            proxy_set_header X-Forwarded-Host   $host;
            proxy_set_header X-Forwarded-Port   $server_port;
            proxy_pass    http://127.0.0.1:10080;
        }
    }

這裏是從 localhost:80 -> localhost:10080 -> nginx:80 -> php-fpm:9000redis

瀏覽 hdcms.test、houdunren.test 顯示laravel首頁,瀏覽hdcms.test/js/app.js查看靜態頁面輸出。sql

四、hyperf快速構建測試

基於 hyperf 構建測試 RESTful API

a.構建過程

【接上】項目目標:
restful-api格式的用戶表查詢,帶身份驗證

一、項目初始化
composer create-project hyperf/hyperf-skelton restful
cd restful 
composer require hyperf/hyperf-devtool
二、建立用戶表
php bin/hyperf.php gen:migration create_users_table 
#填寫 migrations/table.class 內容
php bin/hyperf.php migrate 
php bin/hyperf.php migrate:status
# 添加索引填寫 migrations/xx_update_users_table.class 內容
php bin/hyperf.php migrate 
php bin/hyperf.php migrate:status
可用的字段定義方法
composer require doctrine/dbal //根據報錯,添加修改字段屬性依賴
php bin/hyperf.php migrate:fresh
php bin/hyperf.php migrate:rollback=1
php bin/hyperf.php migrate:status
bug: PHP Fatal error: Uncaught DoctrineDBALDBALException: Unknown database type enum requested, DoctrineDBALPlatformsMySQL80Platform may not support it.
#### migrations/xx_update_users_table.php
    function up(){
        Schema::getConnection()->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
    }
三、建立控制器
# a.index/create/update/delete/select 註解路由,設置請求方法
php bin/hyperf.php gin:controller v1/Users #:文件路徑 app/v1/Users.php
php bin/hyperf.php vendor:publish hyperf/db
#若是刪除報錯,執行 rm -rf runtime/*
./vendor/bin/init-proxy.sh
# 下載配置文件 php bin/hyperf.php vendor:publish hyperf/xx

# b.登陸鑑權中間件
php bin/hyperf.php gen:middleware v1/Oauth
composer require hyperf/session #Oauth.php: process校驗
    if ($this->session->has('id') && $this->session->get('token')){
        return $handler->handle($request);
    }
php bin/hyperf.php gen:controller v1/Login #login方法
    $this->session->clear();

    $this->session->set('id', mt_rand(1,999));
    $this->session->set('token', strtolower(md5($request->server('request_time'))));
    return $response->json(['status'=>0, 'message'=>'Hello login in!']);
    
# c.db:seed數據生成器
php bin/hyperf.php gen:seeder users #填寫 seeders/users.php: run
php bin/hyperf.php db:seed
四、配置路由
Router::addGroup('/v1', function (){
    Router::post('/login', 'App\Controller\v1\Login@login');
    Router::addGroup('/users', function (){
        Router::get('[/]', 'App\Controller\v1\Users@all');
        Router::get('/{id}', 'App\Controller\v1\Users@get');
        Router::post('[/]', 'App\Controller\v1\Users@create');
        Router::put('[/]', 'App\Controller\v1\Users@update');
        Router::delete('[/]', 'App\Controller\v1\Users@delete');

    }, ['middleware' => [\App\Middleware\v1\Oauth::class]]);
});

### 修改404頁面
class CoreMiddleware extends \Hyperf\HttpServer\CoreMiddleware
{
    //Hyperf\HttpServer\CoreMiddleware::class => App\Middleware\CoreMiddleware::class,    #dependencies.php覆蓋原方法
    protected function handleNotFound(ServerRequestInterface $request)
    {
        // 重寫路由找不到的處理邏輯
        return $this->response()->withStatus(404)->withBody(new SwooleStream('page not found...'));
    }
    protected function handleMethodNotAllowed(array $methods, ServerRequestInterface $request)
    {
        // 重寫 HTTP 方法不容許的處理邏輯
        return $this->response()->withStatus(405)->withBody(new SwooleStream('operate not found...'));
    }
}

代碼上傳:
https://github.com/cffycls/default/tree/master/restful

總結

laradock相似線上環境部署,使用了docker-compose編排,對於複雜需求的開發環境,在有緩存的狀況下,能夠快速搭建相對獨立的空間。

自帶phpmyadmin容器很方便。

相關文章
相關標籤/搜索