我有这个项目:
script.sh
:
#!/bin/sh
echo "test"
Dockerfile
:
FROM ubuntu
RUN ["sh", "script.sh"]
使用 build 命令docker build -t test .
,我收到此错误:
=> [internal] load .dockerignore 0.1s
=> => transferring context: 2B 0.0s
=> [internal] load build definition from Dockerfile 0.1s
=> => transferring dockerfile: 118B 0.0s
=> [internal] load metadata for docker.io/library/ubuntu:latest 2.3s
=> [auth] library/ubuntu:pull token for registry-1.docker.io 0.0s
=> CACHED [1/2] FROM docker.io/library/ubuntu@sha256:ec050c32e4a6085b423d36ecd025c0d3ff00c38ab93a3d71a460ff1c44f 0.0s
=> ERROR [2/2] RUN ["sh", "script.sh"] 0.9s
------
> [2/2] RUN ["sh", "script.sh"]:
#0 0.791 sh: 0: cannot open script.sh: No such file
------
Dockerfile:2
--------------------
1 | FROM ubuntu
2 | >>> RUN ["sh", "script.sh"]
--------------------
ERROR: failed to solve: process "sh script.sh" did not complete successfully: exit code: 2
但是,如果我将 Dockerfile 更改为:
FROM ubuntu
CMD ["sh", "script.sh"]
然后它就起作用了:
[+] Building 1.2s (5/5) FINISHED
=> [internal] load build definition from Dockerfile 0.1s
=> => transferring dockerfile: 73B 0.0s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [internal] load metadata for docker.io/library/ubuntu:latest 1.0s
=> CACHED [1/1] FROM docker.io/library/ubuntu@sha256:ec050c32e4a6085b423d36ecd025c0d3ff00c38ab93a3d71a460ff1c44f 0.0s
=> exporting to image 0.0s
=> => exporting layers 0.0s
=> => writing image sha256:d9bf124a17e507c73f6defde7b046fff153fb464c2cad8a57333a0966ddf07c1 0.0s
=> => naming to docker.io/library/test 0.0s
RUN - 命令在我们构建 docker 镜像时触发。
CMD - 当我们启动创建的 docker 镜像时触发命令。
不过,我无法解释为什么 RUN 不起作用而 CMD 起作用。
Docker 不会隐式地将
COPY
内容放入容器中,因此使用您当前的代码,您的容器根本不包含任何script.sh
文件。请考虑:
因为您没有运行,所以
sh
脚本选择的解释器(#!/bin/sh
、、、、或任何它可能想要的其他)将被尊重。(最好删除扩展名,因此,如果您稍后重写为非 shell 语言,则无需在更改调用约定和使用误导性文件名之间进行选择)。#!/usr/bin/bash
#!/usr/bin/env zsh
#!/usr/bin/env python
.sh
请注意,这确实需要您的脚本具有可执行权限和有效的 shebang 行;
chmod +x
如果没有,您可能需要使用。