로컬 소스 코드에서 함수 워크로드 작성
IBM Cloud® Code Engine CLI를 사용하면 로컬 워크스테이션의 소스 코드에서 직접 Code Engine 함수를 생성할 수 있습니다. function create (또는 fn create) 명령을 사용하여 로컬 소스에서 코드 번들을 빌드하고 이 빌드된 코드 번들을 참조하도록 함수를 배치하십시오.
코드 번들은 기능 코드를 나타내는 파일의 콜렉션입니다. 이 코드 번들은 런타임 컨테이너에 삽입됩니다. 코드 번들은 Code Engine 에 의해 작성되며 컨테이너 레지스트리에 저장되거나 함수와 함께 인라인으로 저장됩니다. 코드 번들은 OCI (Open Container Initiative) 표준 컨테이너 이미지가 아닙니다.
로컬 디렉터리에서 코드를 가져오는 빌드를 제출하면 소스 코드가 아카이브 파일로 압축됩니다. ‘ Code Engine ’은 코드 번들을 사용자의 계정에 있는 IBM Cloud® Container Registry 네임스페이스로 자동으로 업로드한 다음, 이 빌드된 코드 번들을 참조하도록 함수를 생성하고 배포합니다. 로컬 빌드의 경우 IBM Cloud Container Registry만 대상으로 지정할 수 있습니다. 이 시나리오에서는 함수
이름과 로컬 소스의 경로만 지정하면 됩니다. 옵션의 전체 목록을 보려면 ibmcloud ce fn create 명령을 참조하십시오.
이미지 레지스트리에 액세스하는 데 필요한 권한에 대한 정보는 이미지 레지스트리의 권한 설정을 참조하십시오.
.gitignore 파일과 유사하게 작동하는 .ceignore 파일을 사용하여 소스 코드 내에서 특정 파일 패턴을 무시하도록 선택할 수 있습니다. 예를 들어, Node.js 함수에 대한 .ceignore 파일의 항목에는 node_modules 및 .npm 등이 포함될 수 있습니다. 무시할 파일 패턴에 대한 더 많은 예시는
GitHub 의.gitignore 저장소를 참조하세요.
IBM Cloud® Container Registry 이 시나리오에서는 필수입니다.
시작하기 전에
- Code Engine CLI 환경을 설정하십시오.
- 프로젝트를 작성하고 작업하십시오.
로컬 소스에 대해 작업하기 전에 소스가 로컬 워크스테이션의 액세스 가능한 위치에 있는지 확인하십시오.
CLI를 사용하여 로컬 소스 코드에서 함수 생성하기
이 예제에서는 main.js 파일로 저장된 다음 Node.js 코드를 사용합니다. 사용자 고유의 코드를 대체할 수 있습니다.
/**
* The `main` function is the entry-point into the function.
* It has one optional argument, which carries all the
* parameters the function was invoked with.
*/
async function main(params) {
// log environment variables available to the function
console.log(process.env);
// log Code Engine system headers available to the function
console.log(params.__ce_headers);
// log all parameters for debugging purposes
console.log("params: "+params);
// since functions are invoked through http(s), we return an HTTP response
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: params };
}
// this step is necessary, if you gave your main function a different name
// we include it here for documentation purposes only
module.exports.main = main;
-
main.js파일을 포함하는 디렉토리로 변경하거나 해당 경로를 기록하십시오. -
main.js파일을 소스로 사용하는myfun-local라는 함수를 작성하십시오. 이 명령어는 코드 번들을 자동으로 빌드하여 사용자의 계정에 있는 Container Registry 네임스페이스로 푸시합니다. 기존 Container Registry 네임스페이스가 없는 경우 Code Engine에서 자동으로 작성합니다.ibmcloud ce fn create --name myfun-local --runtime nodejs --build-source main.js출력 예
Preparing function 'myfun-local' for build push... Creating function 'myfun-local'... Packaging files to upload from source path 'main.js'... Submitting build run 'myfun-local-run-230123-111011111'... Creating image 'icr.io/ce--abcde-glxo4kabcde/function-myfun-local:230123-1650-yrj86'... Waiting for build run to complete... Build run status: 'Running' Build run completed successfully. Run 'ibmcloud ce buildrun get -n myfun-local-run-230626-115011911' to check the build run status. Waiting for function 'myfun-local' to become ready... Function 'myfun-local' is ready. OK Run 'ibmcloud ce function get -n myfun-local' to see more details. https://myfun-local.glxo4kabcde.us-south.codeengine.test.appdomain.cloudfunction create명령의 출력은 함수가 작성되기 전에 빌드 실행의 진행에 대한 정보를 제공합니다.이 예제에서는 빌드된 코드 번들이 Container Registry 의
ce--abcde-glxo4kabcde네임스페이스로 업로드됩니다.다음 표는 이 예제에서
fn create명령과 함께 사용되는 옵션을 요약한 것입니다. 이 명령어와 해당 옵션에 대한 자세한 내용은ibmcloud ce function create명령을 참조하십시오. 이러한 옵션은 소스 코드가 있는 위치에 따라 달라지므로 소스 코드가 예시와 일치하는 위치에 있는지 확인하세요.명령 설명 옵션 설명 --name기능의 이름입니다. 프로젝트 내에서 고유한 이름을 사용하십시오. 이 값은 필수입니다.
- 이름은 소문자로 시작해야 합니다.
- 이름은 소문자 영숫자로 끝나야 합니다.
- 이름은 63자 이하여야 하며 문자, 숫자 및 하이픈(-)을 포함할 수 있습니다.
--build-source로컬 소스의 경로입니다. 이 값은 필수입니다. --runtime이 기능에 사용할 런타임입니다. 이 값은 필수입니다. -
function get명령을 사용하여 빌드 정보를 포함하여 앱에 대한 정보를 표시하십시오.ibmcloud ce function get --name myfun-local출력 예
Getting function 'myfun-local'... OK Name: myfun-local Project Name: sample Project ID: abcdefgh-abcd-abcd-abcd-1a2b3c4d5e6f Age: 5m41s Created: 2023-06-26T16:50:14Z URL: https://myfun-local.glxo4kabcde.us-south.codeengine.test.appdomain.cloud Status: Ready Resources: CPU: 0.25 Memory: 500M Max Execution Time: 60 seconds Build Information: Build Run Name: myfun-local-run-230123-111011111 Build Type: local Build Strategy: codebundle-nodejs-22 Timeout: 600 Source: main.js Build Run Summary: Succeeded Build Run Status: Succeeded Build Run Reason: All Steps have completed executing Run 'ibmcloud ce buildrun get -n myfun-local-run-230123-111011111' for details. Function Code: Runtime: nodejs-22 (managed) Bundle Secret: ce-auto-icr-us-south Code Bundle: cr://icr.io/ce--abcde-glxo4kabcde/function-myfun-local:230123-1650-yrj86 Main: main()
함수에 대한 종속성 포함
여러 프로그래밍 언어로 함수를 작성할 수 있습니다. 함수 코드가 복잡해지면 함수에 대한 종속성으로 코드 모듈을 추가할 수 있습니다. 각 언어에는 기능 코드와 함께 사용할 자체 모듈이 있습니다. 예를 들어, Node.js 종속 항목은 일반적으로 기존 npm 모듈인 반면, Python 은 Python 패키지를 사용합니다. 이러한 종속성은 소스 코드가 있는 파일에서 선언되고 작성되어야 합니다.
Node.js 함수에 대한 모듈 포함
package.json 파일을 작성하여 특정 Node.js 모듈에 대한 종속성을 포함하는 함수를 작성하십시오. 이 경우 소스 코드 및 패키지 파일 모두 동일한 폴더에 있습니다.
-
코드를
main.js파일에 작성하여 소스 코드를 작성하십시오. 예를 들어, 다음 코드 예제를main.js파일에 복사하십시오./** * The `main` function is the entry-point into the function. * It has one optional argument, which carries all the * parameters the function was invoked with. */ function main(params /* optional */) { // use third-party 'lorem-ipsum' package to generate random words const LoremIpsum = require("lorem-ipsum").LoremIpsum; const lorem = new LoremIpsum(); // since functions are invoked through http(s), we return an HTTP response return { headers: { "Content-Type": "text/plain;charset=utf-8" }, body: lorem.generateWords(10), }; } // this step is necessary, if you gave your main function a different name // we include it here for documentation purposes only module.exports.main = main; -
함수에 필요한 종속 항목을 포함하는
package.json파일을 작성하십시오. 이전 코드 예제의 경우package.json파일에 대해 다음 컨텐츠를 사용하십시오.{ "name": "function", "version": "1.0.0", "main": "main.js", "dependencies" : { "lorem-ipsum" : "2.0.8" } } -
Code Engine에서 함수로 파일을 작성하십시오. 이 경우 로컬 파일이 있는 디렉토리에 있으므로
.를 빌드 소스로 사용할 수 있습니다.ibmcloud ce fn create --name nodelorem --runtime nodejs --build-source . -
제공된
fn get명령을 실행하여 기능에 대한 세부사항을 찾으십시오. -
URL 를 웹 브라우저에 붙여넣기하여 기능을 불러내십시오. 브라우저가
lorem ipsum의 단락을 표시합니다.
fn create 명령 및 해당 옵션에 대한 자세한 정보는 함수 작성 을 참조하십시오.
Python 함수에 대한 모듈 포함
requirements.txt 파일을 작성하여 특정 Python 모듈에 대한 종속성을 포함하는 함수를 작성하십시오. 이 경우 소스 코드 및 요구사항 파일 모두 동일한 폴더에 있습니다.
-
코드를
__main__.py파일에 저장하여 함수 작성# use third-party 'lorem-ipsum' package to generate random words from lorem_text import lorem # The `main` function is the entry-point into the function. # It has one optional argument, which carries all the # parameters the function was invoked with. def main(params): words = 10 # since functions are invoked through http(s), we return an HTTP response return { "headers": { "Content-Type": "text/plain;charset=utf-8", }, "body": lorem.words(words), } def main(params): words = 10 return { "headers": { "Content-Type": "text/plain;charset=utf-8", }, "body": lorem.words(words), } -
함수에 필요한 종속 항목을 포함하는
requirements.txt작성lorem-text -
Code Engine에서 함수로 파일을 작성하십시오. 이 경우 로컬 파일이 있는 디렉토리에 있으므로
.를 빌드 소스로 사용할 수 있습니다.ibmcloud ce fn create --name pylorem --runtime python --build-source . -
제공된
fn get명령을 실행하여 기능에 대한 세부사항을 찾으십시오. -
URL 를 웹 브라우저에 붙여넣기하여 기능을 불러내십시오. 브라우저가
lorem ipsum의 단락을 표시합니다.
fn create 명령 및 해당 옵션에 대한 자세한 정보는 함수 작성 을 참조하십시오.
다음 단계
함수가 로컬 소스 코드에서 작성되고 배치되었으므로 ibmcloud ce function update 명령을 사용하여 필요에 맞게 함수를 업데이트할 수 있습니다. --build-source 함수와 함께 사용할 소스를 업데이트하려면,
function update 명령에 xml-ph-0000@deepl.internal 옵션을 지정해야 합니다.
함수가 로컬 소스 또는 CLI의 저장소 소스 코드 에서 배치되는 경우 결과 빌드 실행은 빌드 구성을 기반으로 하지 않습니다. 완료된 빌드 실행은 결국 자동으로 삭제됩니다. 빌드 실행이 성공하면 빌드 구성을 기반으로 하지 않는 빌드 실행이 1시간후에 삭제됩니다. 빌드 실행에 실패하면 이 빌드 실행은 24시간후에 삭제됩니다. CLI를 사용하여 이 빌드 실행에 대한 정보만 표시할 수 있습니다. 콘솔에서는 이 빌드 실행을 볼 수 없습니다.
더 많은 코드 예를 찾고 계십니까? IBM Cloud Code Engine GitHub 저장소의 예제를 확인해 보세요.