在等待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
。
不过有一些注意事项
- 这种方式需要在你的 Cloud Run 服务上配置的服务账号拥有
roles/compute.instanceAdmin
角色,这个功能非常强大。
- SSH 密钥被备份到映像中以加快容器启动时间。这并不理想。
- 如果您的转发器崩溃,则不会进行故障转移。
我在一篇博客文章中写了一个更长、更详细的方法,它提高了整体安全性并增加了故障转移功能。该解决方案使用纯 SSH 而不是gcloud
CLI。