Mac OSX部署AWS Python Lambda时遇Numpy相关Serverless错误
Hey there, I’ve run into this exact problem countless times—here’s the root cause and step-by-step fixes to get your Lambda function running smoothly:
Why This Happens
AWS Lambda runs on an Amazon Linux environment, but when you install Numpy (or any binary-dependent package) directly on your Mac, it compiles for Mac’s architecture. Those Mac-specific binary files won’t work on Lambda’s Linux runtime, which is why you’re seeing that cryptic startup error.
Solution 1: Use Serverless Python Requirements Plugin (Easiest Approach)
This plugin handles cross-platform dependency packaging automatically with Docker, so you don’t have to mess with manual installs:
- First, install the plugin in your project:
serverless plugin install -n serverless-python-requirements - Open your
serverless.ymland add the following configuration to enable Docker-based dependency building:plugins: - serverless-python-requirements custom: pythonRequirements: dockerizePip: non-linux # This triggers Docker builds for non-Linux machines like Mac - Now just re-run your deploy command:
serverless deploy
The plugin will spin up a Lambda-compatible Linux container, install Numpy (and other dependencies) correctly, and package everything up for deployment.
Solution 2: Manual Docker Dependency Installation (If You Prefer No Plugins)
If you want to do it without plugins, use a Lambda build Docker image to install your dependencies:
- Make sure Docker is running on your Mac.
- Navigate to your project directory (with your activated venv), then run this command (replace
python3.8with your Lambda’s Python version):
This mounts your project folder into the Docker container, installs dependencies using Lambda’s Linux environment, and saves them directly to your project directory.docker run -v "$PWD":/var/task lambci/lambda:build-python3.8 pip install -r requirements.txt -t . - Update your
serverless.ymlto exclude your local venv and include the newly installed dependencies:package: exclude: - venv/** - .git/** - __pycache__/** include: - '*.py' - numpy/** - # Add other dependency folders here (like scipy if you use it) - Deploy again with
serverless deploy.
Bonus: Check Version Compatibility
Your Numpy version (1.14.2) is pretty old—double-check that it’s compatible with the Python version you’re using in Lambda. For example, Python 3.9+ requires Numpy 1.19.0 or newer. If you run into further issues, try upgrading Numpy to a compatible version in your requirements.txt.
Verify the Fix
After deployment, test your Lambda function and check the CloudWatch logs for any errors. If everything works, you’re good to go!
内容的提问来源于stack exchange,提问作者Chris Evans

