Templates

The predefined templates may be good enough for strings and developing simple functions, but when things get complex, it is great to know how to tweak OpenFaaS templates by ourselves.

In this section, the Go template will be tweaked to simply reduce the number of build steps as an example. The following Dockerfile of the Go template can be found at template/go/Dockerfile. This Dockerfile already uses the multi-stage build technique:

###################
# State 0
###################
FROM golang:1.8.3-alpine3.6

# ... lines removed for brevity

###################
# State 1
###################
FROM alpine:3.6
RUN apk --no-cache add ca-certificates

# Add non root user
RUN addgroup -S app adduser -S -g app app
mkdir -p /home/app
chown app /home/app

WORKDIR /home/app
COPY --from=0 /go/src/handler/handler .
COPY --from=0 /usr/bin/fwatchdog .

USER app
ENV fprocess="./handler"
CMD ["./fwatchdog"]

Templates can be hosted on a custom Git repository. Here's the structure of a template repository, which can be fetched by the template sub-command. The first level must be a directory named template/. Inside the template directory, there may be a number of directories, for example, go/ in the following structure:

$ tree .
.
├── README.md
└── template
└── go
├── Dockerfile
├── function
│ └── handler.go
├── main.go
├── README.md
└── template.yml

After storing the whole template source in a GitHub repository, it can be pulled for building and tweaking later with faas-cli template pull:

$ faas-cli template pull https://github.com/chanwit/faas-templates
Fetch templates from repository: https://github.com/chanwit/faas-templates
2017/11/16 15:44:46 HTTP GET https://github.com/chanwit/faas-templates/archive/master.zip
2017/11/16 15:44:48 Writing 2Kb to master.zip

2017/11/16 15:44:48 Attempting to expand templates from master.zip
2017/11/16 15:44:48 Fetched 1 template(s) : [go] from https://github.com/chanwit/faas-templates
2017/11/16 15:44:48 Cleaning up zip file...

After pulling the tweaked template, the image can be rebuilt and the number of build steps is reduced to 15:

$ faas-cli build -f hello.yml 
[0] > Building: hello.
Clearing temporary build folder: ./build/hello/
Preparing ./hello/ ./build/hello/function
Building: chanwit/hello:v1 with go template. Please wait..
Sending build context to Docker daemon 7.68kB
Step 1/15 : FROM golang:1.8.3-alpine3.6
---> fd1ada53b403

...

Step 15/15 : CMD ./fwatchdog
---> Using cache
---> 23dfcc80a031
Successfully built 23dfcc80a031
Successfully tagged chanwit/hello:v1
Image: chanwit/hello:v1 built.
[0] < Builder done.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset