在 Docker 中运行 Lua 脚本

我在 Docker 镜像中无法运行 Lua 脚本。

我有一个非常简单的 Lua 脚本需要包含在镜像中:

function main(...)
    print("hello world")
end

我创建了一个 Dockerfile:

FROM debian:latest
RUN apt-get -y update && apt-get -y install lua5.1 lua-socket lua-sec
ADD hello.lua /home/user/bin/hello.lua
CMD ["/bin/sh", "-c", “lua /home/user/bin/hello.lua”]

但是当我尝试运行 Docker 镜像时,我会收到以下错误:

/bin/sh: 1: [/bin/sh,: not found

是否有一个合理的解释为什么会出现这个错误,以及如何在运行 Docker 镜像时使脚本运行?

点赞
用户5902456
用户5902456

你可以直接在 Dockerfile 中使用 lua 命令作为 CMD:

CMD ["lua", "/home/user/bin/hello.lua"]
2016-11-21 08:24:21
用户2060502
用户2060502

你的 Dockerfile 的最后一行应该是

CMD ["lua", "/home/user/bin/hello.lua"]

记住,你的 hello.lua 不会打印出任何内容。 它定义了一个主函数,但在该例子中未被调用。

它不是 Python,在 Lua 中,调用 lua 文件时会调用主代码块。 如果你想从命令行传递参数:

CMD ["lua", "/home/user/bin/hello.lua", "param1"]

hello.lua:

-- 将所有传入的参数放入表中
local params = {...}

-- 如果有参数,打印第一个参数
print(params[1])
2016-11-21 11:00:26
用户596285
用户596285

你最终的命令中有智能引号在 lua 命令周围。这些是无效的 JSON 字符:

CMD ["/bin/sh", "-c", “lua /home/user/bin/hello.lua”]

因此,Docker 正在尝试执行该字符串,并抛出缺少 [/bin/sh 的错误。把引号改成普通引号(并且避免使用添加这些引号的任何编辑器):

CMD ["/bin/sh", "-c", "lua /home/user/bin/hello.lua"]

正如其他人提到的,你可以完全跳过 shell:

CMD ["lua", "/home/user/bin/hello.lua"]

并且你的 hello.lua 主函数将不会被调用,因此你可以将其简化为你想要运行的命令:

print("hello world")

最终,你会看到类似以下的内容:

$ cat hello.lua
print("hello world")

$ cat Dockerfile
FROM debian:latest
RUN apt-get -y update && apt-get -y install lua5.1 lua-socket lua-sec
ADD hello.lua /home/user/bin/hello.lua
CMD ["lua", "/home/user/bin/hello.lua"]

$ docker build -t luatest .
Sending build context to Docker daemon 3.072 kB
Step 1 : FROM debian:latest
 ---> 7b0a06c805e8
Step 2 : RUN apt-get -y update && apt-get -y install lua5.1 lua-socket lua-sec
 ---> Using cache
 ---> 0634e4608b04
Step 3 : ADD hello.lua /home/user/bin/hello.lua
 ---> Using cache
 ---> 35fd4ca7f0f0
Step 4 : CMD /bin/sh -c lua /home/user/bin/hello.lua
 ---> Using cache
 ---> 440098465ee4
Successfully built 440098465ee4

$ docker run -it luatest
hello world
2016-11-21 12:17:07