我正在尝试创建一个 Docker 镜像AWS SAM CLI https://github.com/awslabs/aws-sam-cli,但调用任何函数都会出现错误:“无法导入模块‘index’”。我可以在 Docker 之外成功运行相同的测试用例。您可以克隆测试用例here https://github.com/dc7/docker-sam-local或查看下面的文件。
我已经尝试过以下操作:
- 将文件和父文件夹的权限设置为777(或755)。
- 在 Docker 守护进程中禁用(或启用)SELinux。
- 在特权模式(或非特权模式)下运行 Docker。
- 我使用旧的(SAM 0.22)得到同样的错误Docker镜像 https://hub.docker.com/r/cnadiminti/aws-sam-local/.
- 如下所述在本地运行相同的函数(有效)。
- 压缩文件夹并在 AWS 上运行(有效)。
这些解决方案可能不适用:
- zip 文件的格式不正确,包括父文件夹(未使用 zip 文件)。
- 与 NPM 依赖项或 node_modules 相关的问题(index.js 没有依赖项)。
- index.js 中的编译错误(语法正确,可以在 Docker 之外和 AWS 上运行)。
- 卷正在按照描述安装在主机上here https://github.com/awslabs/aws-sam-cli#remote-docker.
Dockerfile
FROM alpine:3.6
WORKDIR /usr/src/app
RUN apk add --no-cache py-pip
RUN pip install --no-cache-dir aws-sam-cli
事件.json
{}
index.js
exports.handler = function(event, context, callback) {
return callback(null, {
'body': 'Hello, World!'
});
};
模板.yml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
HelloWorld:
Type: AWS::Serverless::Function
Properties:
FunctionName: HelloWorld
CodeUri: .
Handler: index.handler
Runtime: nodejs6.10
Timeout: 300
要在本地运行 SAM:
sam local invoke -t template.yml -e event.json HelloWorld
本地运行 SAM 成功:
{"body":"Hello, World!"}
要在 Docker 下运行 SAM:
docker build -t hello .
docker run \
-v $(pwd):/usr/src/app \
-v /var/run/docker.sock:/var/run/docker.sock \
hello sam local invoke -t template.yml -e event.json HelloWorld
在 Docker 下运行 SAM 失败:
Unable to import module 'index': Error
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
操作系统:Ubuntu 16.04.1 x86_64
Docker 版本:18.03.1-ce
SAM CLI 版本:0.3.0