从云端连接到 Memorystore 运行

Connect to Memorystore from Cloud Run

我想 运行 Google Cloud 运行 上的一项服务,该服务使用 Cloud Memorystore 作为缓存。

我在与 Cloud 运行 相同的区域创建了一个 Memorystore 实例,并使用示例代码进行连接:https://github.com/GoogleCloudPlatform/golang-samples/blob/master/memorystore/redis/main.go 这没有用。

接下来我创建了一个无服务器 VPC 访问连接器,但没有帮助。我在没有 GKE 集群的情况下使用 Cloud 运行,因此我无法更改任何配置。

有没有办法从 Cloud 运行 Memorystore 连接?

要将 Cloud 运行(完全托管)连接到 Memorystore,您需要使用称为 "Serverless VPC Access" 或 "VPC Connector".

的机制

截至 2020 年 5 月,云 运行(完全托管)对无服务器 VPC 访问提供 Beta 支持。有关详细信息,请参阅 Connecting to a VPC Network

使用此 Beta 的替代方案包括:

如果您的 VPC 中需要一些东西,您也可以启动 Redis on Compute Engine

它比 Redis Cloud 成本更高(尤其是对于集群而言)- 但如果您必须将数据保存在 VPC 中,这是一个临时解决方案。

在等待 serverless VPC connectors on Cloud Run 期间 - Google 昨天表示将在近期发布公告 - 您可以通过 GCE 使用 SSH 隧道从云 运行 连接到 Memorystore。

基本方法如下。

首先在GCE上创建一个forwarder实例

gcloud compute instances create vpc-forwarder --machine-type=f1-micro --zone=us-central1-a

不要忘记在防火墙策略中打开端口 22(默认打开)。

然后通过您的 Dockerfile 安装 gcloud CLI

这是 Rails 应用程序的示例。 Dockerfile 使用脚本作为入口点。

# Use the official lightweight Ruby image.
# https://hub.docker.com/_/ruby
FROM ruby:2.5.5

# Install gcloud
RUN curl https://dl.google.com/dl/cloudsdk/release/google-cloud-sdk.tar.gz > /tmp/google-cloud-sdk.tar.gz
RUN mkdir -p /usr/local/gcloud \
  && tar -C /usr/local/gcloud -xvf /tmp/google-cloud-sdk.tar.gz \
  && /usr/local/gcloud/google-cloud-sdk/install.sh
ENV PATH $PATH:/usr/local/gcloud/google-cloud-sdk/bin

# Generate SSH key to be used by the SSH tunnel (see entrypoint.sh)
RUN mkdir -p /home/.ssh && ssh-keygen -b 2048 -t rsa -f /home/.ssh/google_compute_engine -q -N ""

# Install bundler
RUN gem update --system
RUN gem install bundler

# Install production dependencies.
WORKDIR /usr/src/app
COPY Gemfile Gemfile.lock ./
ENV BUNDLE_FROZEN=true
RUN bundle install

# Copy local code to the container image.
COPY . ./

# Run the web service on container startup.
CMD ["bash", "entrypoint.sh"]

最终在您的 entrypoint.sh 脚本中打开到 Redis 的 SSH 隧道


# !/bin/bash

# Memorystore config
MEMORYSTORE_IP=10.0.0.5
MEMORYSTORE_REMOTE_PORT=6379
MEMORYSTORE_LOCAL_PORT=6379

# Forwarder config
FORWARDER_ID=vpc-forwarder
FORWARDER_ZONE=us-central1-a

# Start tunnel to Redis Memorystore in background
gcloud compute ssh \
  --zone=${FORWARDER_ZONE} \
  --ssh-flag="-N -L ${MEMORYSTORE_LOCAL_PORT}:${MEMORYSTORE_IP}:${MEMORYSTORE_REMOTE_PORT}" \
  ${FORWARDER_ID} &

# Run migrations and start Puma
bundle exec rake db:migrate && bundle exec puma -p 8080

通过上述解决方案,Memorystore 将在 localhost:6379 上对您的应用程序可用。

不过有一些注意事项

  1. 这种方法需要在你的云运行服务上配置的服务帐户具有roles/compute.instanceAdmin角色,这是相当强大的。
  2. 将 SSH 密钥备份到映像中以加快容器启动时间。这并不理想。
  3. 如果您的转发器崩溃,则不会进行故障转移。

我在 blog post 中编写了一个更长、更详细的方法,它提高了整体安全性并增加了故障转移功能。该解决方案使用纯 SSH 而不是 gcloud CLI。