【问题标题】:How to execute ps1 script using docker run command?如何使用 docker run 命令执行 ps1 脚本?
【发布时间】:2019-11-26 14:30:45
【问题描述】:

我需要使用官方的 PowerShell Core Docker 镜像来运行一个 Docker 容器并让它执行一个 PowerShell 脚本文件。

我知道可以使用 Dockerfile 和 Docker 构建来完成,但在这种情况下不能使用。

通过阅读文档我想出了这个,但它似乎不起作用:

docker run -it --rm --entrypoint "/tmp/test.ps1" repo/powershell:latest

docker: Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"/tmp/test.ps1\": stat /tmp/test.ps1: no such file or directory": unknown.
ERRO[0001] error waiting for container: context canceled

错误似乎说它找不到文件,但手动运行stat "/tmp/test.ps1" 时它工作正常。

我觉得二进制 pwsh 也应该指定,但找不到方法。

【问题讨论】:

  • 我通常会像这样在 docker 内部运行:docker run -it repo/powershell:latest /tmp/test.ps,因为你不需要留在里面 -it 不是必需的
  • 您好,感谢您的评论。试过了,但它给出了同样的错误:docker run repo/powershell:latest /tmp/test.ps1 docker: Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"/tmp/test.ps1\": stat /tmp/test.ps1: no such file or directory": unknown.
  • 之后尝试stat 命令:rob@linuxvm:/tmp$ stat /tmp/test.ps1 File: /tmp/test.ps1 Size: 32 Blocks: 8 IO Block: 4096 regular file Device: 802h/2050d Inode: 931983 Links: 1 Access: (0664/-rw-rw-r--) Uid: ( 1000/ rob) Gid: ( 1000/ rob) Access: 2019-11-26 15:55:56.966119943 +0000 Modify: 2019-11-26 15:56:07.951610246 +0000 Change: 2019-11-26 15:56:07.951610246 +0000 Birth: -
  • 刚刚意识到stat /tmp/test.ps1: no such file or directory powershell - 表示windows,这意味着/tmp/test.ps1 不是从根目录的绝对路径。如果是这样,您应该尝试类似C:\bla\bla\another_bla\tmp\test.ps1
  • 我正在使用带有 Docker 的 Ubuntu 主机。 PowerShell Core 映像来自 Docker 中心。而且我相信 ps1 文件位于正确的目录中,是 Linux 的新手,所以可能有错误,但是在目录中执行 pwd 会返回 /tmp/ 所以它不是 /home/user/tmp 之类的。

标签: powershell docker devops powershell-core docker-run


【解决方案1】:

docker run -it mcr.microsoft.com/powershell pwsh -c "Write-Host 'Hello, World'"

这会产生Hello, World

而mcr.microsoft.com/powershell 是谷歌返回的official PowerShell Core Docker image

这张图片里面没有文件/tmp/test.ps1。所以不太清楚repo/powershell:latest 里面有什么图片。

  • 如果您尝试读取文件并在 docker 内部执行,那么这对我来说效果很好:
docker run -it --rm mcr.microsoft.com/powershell pwsh -c $(cat test.ps)
  • 或者,如果您尝试将主机文件传递到容器中并执行,您可以将本地路径映射到容器内部的路径,而不是这样:
docker run -v /tmp/localdata:/tmp/containerdata  -it --rm mcr.microsoft.com/powershell pwsh /tmp/containerdata/test.ps

假设您在主机上拥有 /tmp/localdata 文件夹,其中包含带有 Write-Host 'Hello, World!' 文本的 test.ps 文件。

两种方式的结果都是Hello, World

【讨论】:

  • 谢谢!最后一个有卷的就成功了,我试图从主机传递一个文件,很抱歉造成的混乱,我认为--entrypoint 就是为了做到这一点。不知何故错过了文档中有关卷的部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 2018-03-03
相关资源
最近更新 更多