在Windows中使用 Docker 容器运行项目时发现,发现响应速度特别慢,这特别影响我们的开发效率,这是由于WSL2跨系统文件读写性能差的原因。
Docker是跑在 WSL2 里的,虽说 WSL2 相比 WSL1 更先进,但在跨系统文件读写性能方面是比 WSL1 差的,因此,跑在 WSL2 里的Docker想要跨系统访问Windows系统上的代码文件的话,性能是很差的。
Docker Engine Use WSL2
Docker 设置中勾选Use the WSL 2 based engine,使用WSL2

项目初始化
在WSL2 Linux发行版中创建项目
# 进入Linux发行版
wsl
# 创建项目目录
mkdir -p /data/www
cd /data/www
# 从git仓库中拉取项目
git clone https://github.com/laravel/laravel.git

Docker-compose构建容器
docker-compose.yaml
version: '1.0'
services:
php74:
image: registry.cn-hangzhou.aliyuncs.com/cqcqs/php74-fpm
container_name: php74
restart: always
ports:
- 9000:9000
volumes:
- /data/www/laravel:/var/www/html
networks:
net:
ipv4_address: 172.18.0.11
nginx:
image: nginx
container_name: nginx
restart: always
ports:
- 80:80
volumes:
- /data/www/laravel:/var/www/html
- /data/www/nginx.conf:/etc/nginx/conf.d/default.conf
working_dir: /var/www/html
links:
- php7
networks:
net:
ipv4_address: 172.18.0.13
networks:
net:
driver: bridge
ipam:
driver: default
config:
- subnet: 172.19.0.0/24
nginx.conf:
server {
listen 80;
root /var/www/html/public;
error_log /var/log/nginx/error.log;
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 php7:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
构建 docker-compose
docker-compose up -d

composer install
由于我的发行版上没有安装PHP Composer,就直接进入PHP容器安装Laravel项目依赖
# 进入PHP容器
docker exec -it php74
# 安装composer包
composer install
php artisan key:generate

PHPStorm 开发
先在Linux发行版,项目目录中设置权限,否则PHPStorm无法编辑
chmod -R 777 ./
PHPStorm -> Open -> 输入\\wsl$\Ubuntu打开项目目录

完成
浏览器打开http://127.0.0.1/,可见速度提升了很多

网友评论