Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Apr 29, 2024. It is now read-only.

Commit 0b295aa

Browse files
author
bls20AWS
committed
php OCI example
1 parent f54a3fd commit 0b295aa

File tree

9 files changed

+288
-0
lines changed

9 files changed

+288
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#Lambda base image Amazon linux
2+
FROM public.ecr.aws/lambda/provided as builder
3+
# Set desired PHP Version
4+
ARG php_version="7.3.6"
5+
RUN yum clean all && \
6+
yum install -y autoconf \
7+
bison \
8+
bzip2-devel \
9+
gcc \
10+
gcc-c++ \
11+
git \
12+
gzip \
13+
libcurl-devel \
14+
libxml2-devel \
15+
make \
16+
openssl-devel \
17+
tar \
18+
unzip \
19+
zip
20+
21+
# Download the PHP source, compile, and install both PHP and Composer
22+
RUN curl -sL https://github.com/php/php-src/archive/php-${php_version}.tar.gz | tar -xvz && \
23+
cd php-src-php-${php_version} && \
24+
./buildconf --force && \
25+
./configure --prefix=/opt/php-7-bin/ --with-openssl --with-curl --with-zlib --without-pear --enable-bcmath --with-bz2 --enable-mbstring --with-mysqli && \
26+
make -j 5 && \
27+
make install && \
28+
/opt/php-7-bin/bin/php -v && \
29+
curl -sS https://getcomposer.org/installer | /opt/php-7-bin/bin/php -- --install-dir=/opt/php-7-bin/bin/ --filename=composer
30+
31+
# Prepare runtime files
32+
# RUN mkdir -p /lambda-php-runtime/bin && \
33+
# cp /opt/php-7-bin/bin/php /lambda-php-runtime/bin/php
34+
COPY runtime/bootstrap /lambda-php-runtime/
35+
RUN chmod 0755 /lambda-php-runtime/bootstrap
36+
37+
# Install Guzzle, prepare vendor files
38+
RUN mkdir /lambda-php-vendor && \
39+
cd /lambda-php-vendor && \
40+
/opt/php-7-bin/bin/php /opt/php-7-bin/bin/composer require guzzlehttp/guzzle
41+
42+
43+
###### Create runtime image ######
44+
FROM public.ecr.aws/lambda/provided as runtime
45+
# Layer 1: PHP Binaries
46+
COPY --from=builder /opt/php-7-bin /var/lang
47+
# Layer 2: Runtime Interface Client
48+
COPY --from=builder /lambda-php-runtime /var/runtime
49+
# Layer 3: Vendor
50+
COPY --from=builder /lambda-php-vendor/vendor /opt/vendor
51+
52+
COPY src/ /var/task/
53+
54+
CMD [ "index" ]
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
# php-lambda-container-demo
2+
3+
This project contains source code and supporting files for a serverless application that you can deploy with the AWS Serverless Application Model (AWS SAM) command line interface (CLI). It contains a custom runtime PHP Lambda function packaged as a docker contaier image. It deploys an Amazon HTTPs API endpoint to invoke the Lambda function.
4+
5+
The following files and folders are included:
6+
7+
* [runtime/](./0.7-PHP-Lambda-functions-with-Docker-container-images/runtime), code for the custom runtime bootstrap file
8+
* [bootstrap](./0.7-PHP-Lambda-functions-with-Docker-container-images/runtime/bootstrap), a custom bootstrap file implementing the Lambda Runtime API.
9+
* [src/](./0.7-PHP-Lambda-functions-with-Docker-container-images/src), code for the application's Lambda function.
10+
* [index.php](./0.7-PHP-Lambda-functions-with-Docker-container-images/src/index.php), a PHP Lambda function handler
11+
* [Dockerfile](./0.7-PHP-Lambda-functions-with-Docker-container-images/Dockerfile), a docker file containg commands to assemble an image for a custom Lambda runtime for PHP
12+
* [readme.md](./0.7-PHP-Lambda-functions-with-Docker-container-images/readme.md) This file.
13+
14+
15+
## Testing locally
16+
1. Build the previous custom runtime image using the Docker build command:
17+
```bash
18+
docker build -t phpmyfuntion .
19+
```
20+
21+
2. Run the function locally using the Docker run command, bound to port 9000:
22+
```bash
23+
docker run -p 9000:8080 phpmyfuntion:latest
24+
```
25+
26+
3. This command starts up a local endpoint at `localhost:9000/2015-03-31/functions/function/invocations`
27+
28+
29+
4. Post an event to this endpoint using a curl command. The Lambda function payload is provided by using the -d flag. This is a valid Json object required by the Runtime Interface Emulator:
30+
31+
```bash
32+
curl "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{"queryStringParameters": {"name":"Ben"}}'
33+
```
34+
35+
5. A 200 status response is returned:
36+
37+
![post-oci](../repository-resources/postOci.png)
38+
39+
40+
## Deploy the sample application
41+
42+
The AWS SAM CLI is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API.
43+
44+
To use the AWS SAM CLI, you need the following tools:
45+
46+
* AWS SAM CLI - [Install the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html).
47+
* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community).
48+
49+
This [Dockerfile](./0.7-PHP-Lambda-functions-with-Docker-container-images/Dockerfile),) uses the base image for Amazon Linux provided by AWS. The instructions perform the following:
50+
51+
1. Install system-wide Linux packages (zip, curl, tar).
52+
1. Download and compile PHP.
53+
1. Download and install composer dependency manager and dependencies.
54+
1. Move PHP binaries, bootstrap, and vendor dependencies into a directory that Lambda can read from.
55+
1. Set the container entrypoint.
56+
57+
58+
59+
60+
## Deploy the sample application
61+
62+
1. Use the AWS CLI to create a new ECR repository to store the container image for the phpLambdaFuncton.
63+
64+
```bash
65+
aws ecr create-repository --repository-name php-lambda-functon \
66+
--image-tag-mutability IMMUTABLE --image-scanning-configuration scanOnPush=true
67+
```
68+
![create-repository-output](../repository-resources/repositryUrl.png)
69+
70+
Make a note of the repositoryUri as you need it in the next step.
71+
72+
2. Authenticate the Docker CLI to your Amazon ECR registry.
73+
74+
``` bash
75+
aws ecr get-login-password --region {region} | docker login --username AWS --password-stdin {yourAccountID}.dkr.ecr.{region} .amazonaws.com
76+
```
77+
3. Build the application locally
78+
```bash
79+
sam build
80+
```
81+
82+
4. Use the guided version of the sam deploy command and follow these steps:
83+
84+
```bash
85+
sam deploy -g
86+
```
87+
* For Stack Name, enter my-php-lambda-container-demo.
88+
* Choose the same Region that you created the ECR repository in.
89+
* Enter the Image Repository for the HelloWorldFunction (this is the repositoryUri of the ECR repository).
90+
* For Confirm changes before deploy and Allow SAM CLI IAM role creation, keep the defaults.
91+
* For HelloWorldFunction may not have authorization defined, Is this okay? Select Y.
92+
* Keep the defaults for the remaining prompts:
93+
![Sam-deploy-oci](../repository-resources/samDeployOci.png)
94+
95+
5. The output displays the HTTP APIs endpoint:
96+
![sam-oci-output](../repository-resources/samOciOutput.png)
97+
98+
99+
## Cleanup
100+
101+
To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following:
102+
103+
```bash
104+
aws cloudformation delete-stack --stack-name my-php-lambda-container-demo
105+
```
106+
107+
## Resources
108+
109+
For an introduction to the AWS SAM specification, the AWS SAM CLI, and serverless application concepts, see the [AWS SAM Developer Guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html).
110+
Next, you can use the AWS Serverless Application Repository to deploy ready-to-use apps that go beyond Hello World samples and learn how authors developed their applications. For more information, see the [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/) and the [AWS Serverless Application Repository Developer Guide](https://docs.aws.amazon.com/serverlessrepo/latest/devguide/what-is-serverlessrepo.html).
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#!/var/lang/bin/php
2+
3+
<?php
4+
/* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5+
Permission is hereby granted, free of charge, to any person obtaining a copy of this
6+
software and associated documentation files (the "Software"), to deal in the Software
7+
without restriction, including without limitation the rights to use, copy, modify,
8+
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
9+
permit persons to whom the Software is furnished to do so.
10+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
11+
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
12+
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
13+
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
14+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
15+
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
16+
*/
17+
18+
// This invokes Composer's autoloader so that we'll be able to use Guzzle and any other 3rd party libraries we need.
19+
$vendor_dir = '/opt/vendor';
20+
require $vendor_dir . '/autoload.php';
21+
22+
// This is the request processing loop. Barring unrecoverable failure, this loop runs until the environment shuts down.
23+
do {
24+
// Ask the runtime API for a request to handle.
25+
$request = getNextRequest();
26+
27+
// Obtain the function name from the _HANDLER environment variable and ensure the function's code is available.
28+
$handlerFunction = $_ENV['_HANDLER'];
29+
require_once $_ENV['LAMBDA_TASK_ROOT'] . '/' . $handlerFunction . '.php';
30+
31+
// Execute the desired function and obtain the response.
32+
$response = $handlerFunction($request['payload']);
33+
34+
// Submit the response back to the runtime API.
35+
sendResponse($request['invocationId'], $response);
36+
} while (true);
37+
38+
function getNextRequest()
39+
{
40+
$client = new \GuzzleHttp\Client();
41+
$response = $client->get('http://' . $_ENV['AWS_LAMBDA_RUNTIME_API'] . '/2018-06-01/runtime/invocation/next');
42+
43+
return [
44+
'invocationId' => $response->getHeader('Lambda-Runtime-Aws-Request-Id')[0],
45+
'payload' => json_decode((string) $response->getBody(), true)
46+
];
47+
}
48+
49+
function sendResponse($invocationId, $response)
50+
{
51+
$client = new \GuzzleHttp\Client();
52+
$client->post(
53+
'http://' . $_ENV['AWS_LAMBDA_RUNTIME_API'] . '/2018-06-01/runtime/invocation/' . $invocationId . '/response',
54+
['body' => $response]
55+
);
56+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
3+
//hello function
4+
function index($data)
5+
{
6+
return APIResponse("Hello, ". $data['queryStringParameters']['name']);
7+
}
8+
9+
function APIResponse($body)
10+
{
11+
$headers = array(
12+
"Content-Type"=>"application/json",
13+
"Access-Control-Allow-Origin"=>"*",
14+
"Access-Control-Allow-Headers"=>"Content-Type",
15+
"Access-Control-Allow-Methods" =>"OPTIONS,POST"
16+
);
17+
return json_encode(array(
18+
"statusCode"=>200,
19+
"headers"=>$headers,
20+
"body"=>$body
21+
));
22+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
AWSTemplateFormatVersion: '2010年09月09日'
2+
Transform: AWS::Serverless-2016年10月31日
3+
Description: >
4+
ociphp2
5+
6+
Sample SAM Template for ociphp3
7+
8+
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
9+
Globals:
10+
Function:
11+
Timeout: 3
12+
13+
Resources:
14+
myPHPLambdaFuncton:
15+
Type: AWS::Serverless::Function
16+
Properties:
17+
PackageType: Image
18+
Events:
19+
DynamicRequestsRoot:
20+
Type: HttpApi
21+
Properties:
22+
Path: /
23+
Method: ANY
24+
DynamicRequestsProxy:
25+
Type: HttpApi
26+
Properties:
27+
Path: /{proxy+}
28+
Method: ANY
29+
Metadata:
30+
DockerTag: phpoci
31+
DockerContext: ./
32+
Dockerfile: Dockerfile
33+
34+
Outputs:
35+
# ServerlessHttpApi is an implicit API created out of Events key under Serverless::Function
36+
# Find out more about other implicit resources you can reference within SAM
37+
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
38+
HelloWorldApi:
39+
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
40+
Value: !Sub "https://${ServerlessHttpApi}.execute-api.${AWS::Region}.amazonaws.com/"
41+
HelloWorldFunction:
42+
Description: "Hello World Lambda Function ARN"
43+
Value: !GetAtt myPHPLambdaFuncton.Arn
44+
HelloWorldFunctionIamRole:
45+
Description: "Implicit IAM Role created for Hello World function"
46+
Value: !GetAtt myPHPLambdaFuncton.Arn

‎repository-resources/SamOciOutput.png

124 KB
Loading[フレーム]

‎repository-resources/postOCI.png

45.6 KB
Loading[フレーム]

‎repository-resources/repositryUrl.png

91.1 KB
Loading[フレーム]

‎repository-resources/samDeployOci.png

185 KB
Loading[フレーム]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /