17

我想在使用 Cloud Memorystore 作为缓存的 Google Cloud Run 上运行服务。

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

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

有没有办法从 Cloud Run 连接到 Memorystore?

4

3 回答 3

19

要将 Cloud Run(完全托管)连接到 Memorystore,您需要使用称为“无服务器 VPC 访问”或“VPC 连接器”的机制。

自 2020 年 5 月起,Cloud Run(完全托管)为无服务器 VPC 访问提供 Beta 版支持。有关更多信息,请参阅连接到 VPC 网络

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

于 2019-05-20T17:24:13.873 回答
4

在等待Cloud Run 上的无服务器 VPC 连接器时——Google 昨天表示将在短期内发布公告——你可以通过 GCE 使用 SSH 隧道从 Cloud Run 连接到 Memorystore。

基本方法如下。

首先,在GCE上创建一个转发器实例

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. 这种方式需要在你的 Cloud Run 服务上配置的服务账号拥有roles/compute.instanceAdmin角色,这个功能非常强大。
  2. SSH 密钥被备份到映像中以加快容器启动时间。这并不理想。
  3. 如果您的转发器崩溃,则不会进行故障转移。

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

于 2020-04-26T06:25:13.910 回答
2

如果您需要 VPC 中的某些内容,还可以在 Compute Engine 上启动 Redis

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

于 2019-10-08T17:21:44.810 回答