|
| 1 | +# Run a Function in a Docker Container |
| 2 | + |
| 3 | +To run your function in a container, create a `Dockerfile` with the following contents: |
| 4 | + |
| 5 | +```Dockerfile |
| 6 | +# Use the official Node.js 10 image. |
| 7 | +# https://hub.docker.com/_/node |
| 8 | +FROM node:10 |
| 9 | +# Create and change to the app directory. |
| 10 | +WORKDIR /usr/src/app |
| 11 | +# Copy application dependency manifests to the container image. |
| 12 | +# A wildcard is used to ensure both package.json AND package-lock.json are copied. |
| 13 | +# Copying this separately prevents re-running npm install on every code change. |
| 14 | +COPY package.json package*.json ./ |
| 15 | +# Install production dependencies. |
| 16 | +RUN npm install --only=production |
| 17 | +# Copy local code to the container image. |
| 18 | +COPY . . |
| 19 | +# Run the web service on container startup. |
| 20 | +CMD [ "npm", "start" ] |
| 21 | +``` |
| 22 | + |
| 23 | +Start the container locally by running `docker build` and `docker run`: |
| 24 | + |
| 25 | +```sh |
| 26 | +docker build -t helloworld . && docker run --rm -p 8080:8080 helloworld |
| 27 | +``` |
| 28 | + |
| 29 | +Send requests to this function using `curl` from another terminal window: |
| 30 | + |
| 31 | +```sh |
| 32 | +curl localhost:8080 |
| 33 | +# Output: Hello, World |
| 34 | +``` |
| 35 | + |
| 36 | +## Configure gcloud |
| 37 | + |
| 38 | +To use Docker with gcloud, (configure the Docker credential helper](https://cloud.google.com/container-registry/docs/advanced-authentication): |
| 39 | + |
| 40 | +```sh |
| 41 | +gcloud auth configure-docker |
| 42 | +``` |
| 43 | + |
| 44 | +## Deploy a Container |
| 45 | + |
| 46 | +You can deploy your containerized function to Cloud Run by following the [Cloud Run quickstart](https://cloud.google.com/run/docs/quickstarts/build-and-deploy). |
| 47 | + |
| 48 | +Use the `docker` and `gcloud` CLIs to build and deploy a container to Cloud Run, replacing the project id `$GOOGLE_CLOUD_PROJECT` and image name `helloworld`: |
| 49 | + |
| 50 | +```sh |
| 51 | +docker build -t gcr.io/$GOOGLE_CLOUD_PROJECT/helloworld . |
| 52 | +docker push gcr.io/$GOOGLE_CLOUD_PROJECT/helloworld |
| 53 | +gcloud beta run deploy helloworld --image gcr.io/$GOOGLE_CLOUD_PROJECT/helloworld --region us-central1 |
| 54 | +``` |
| 55 | + |
| 56 | +If you want even more control over the environment, you can [deploy your container image to Cloud Run on GKE](https://cloud.google.com/run/docs/quickstarts/prebuilt-deploy-gke). With Cloud Run on GKE, you can run your function on a GKE cluster, which gives you additional control over the environment (including use of GPU-based instances, longer timeouts and more). |
0 commit comments