郭靈紋

Windows 快捷执行 Docker 容器内命令

Laravel Sail 是个轻量级的命令行界面,用来与Laravel默认的Docker开发环境进行交互。但是其仅支持Linux及Mac,且其只能用来于Lavarel默认的Docker开发环境进行交互。受其启发,决定实现一个Windows下的PowerShell脚本,来与自定义的Docker容器进行交互。

代理命令

新建一个ps1脚本,内容参考如下:

sail.ps1

$dir = Get-Location
$linux_dir = "$dir".Remove(0,2) -replace "\\","/"
docker exec kit_php8_1 sh -c "cd $linux_dir && $args"

设置别名

先查看profile文件的位置

PS C:\Users\admin> echo $PROFILE
C:\Users\admin\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

默认情况下这个文件是不存在的,新建该文件:

Microsoft.PowerShell_profile.ps1

Set-Alias -Name sail -Value D:\docker\kit\sail.ps1

打开管理员权限的PowerShell,执行下面的命令,赋予权限即可

Set-ExecutionPolicy RemoteSigned

使用

在PowerShell中执行例如 sail php -v 或者 sail composer install 就可以得到想要的结果。

PS D:\www\example> sail php -v
PHP 8.0.0 (cli) (built: Dec 17 2020 08:54:56) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.0.0-dev, Copyright (c) Zend Technologies
with Xdebug v3.0.2, Copyright (c) 2002-2021, by Derick Rethans
PS D:\www\example>

使用 PhpStorm 等IDE时,如果默认的 Terminal 不是PowerShell。可以找一下设置,改为PowerShell。PowerShell默认位置是 C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe