什么是VPC product 和 非 VPC product
在GCP 上, VPC product 指的是属于某个制定的vpc subnet, 具有至少1个 该 subnet 的内网ip的产品
常见的例如:
- compute engine / MIG (managed instances group)
- 某些dataflow job (指定了 可选参数subnet )
- Cloud Composer (基于airflow)
而 Non VPC product 通常是1个共用产品和 server less 的平台,
例如:
4. Cloud Run
5. Pubsub
6. BigQuery
又 VPC product 去访问 Non VPC product 是很简单的, 因为Non VPC product 都具有1个可以由任何地方访问的google 的domain Name.
例如Pubsub 的topic url:
https://pubsub.googleapis.com/v1/projects/jason-hsbc/topics/TopicA:publish
而由 Non VPC product 去访问 VPC product 并不简单, 就如外网和内网的关系, 外网无法通过内网的ip 去访问内网的资源
而VPC Access/Connector 就是为了解决这个问题而存在的
本文会用cloud run的service 作为例子
场景介绍
1个mysql instance 部署在了1一台vm
vm 名字: tf-vpc0-subnet0-mysql0
所属subnet: vpc0-subnet0
内网ip: 192.168.0.51
但是这种情况下, 我家里的电脑的应用是不能直接访问这个mysql instance的。
为了解决这个问题, 我在另1个有外网ip的vm主机设置了1个 sqlproxy , 反向代理了这个mysql instance.
具体参考:
使用 proxySQL 来代理 Mysql
所以对于这个mysql instance
它是具有两个ip的
1个是内网ip 192.168.0.51
1个是外网ip 34.39.2.90
这样我家里的电脑就可以访问这个mysql instance
让spring boot service 可以return 当前的db instance
利用actuator 库, 让/info 接口return db的连接信息:
@Component
@Slf4j
public class AppVersionInfo implements InfoContributor {
@Value("${pom.version}") // https://stackoverflow.com/questions/3697449/retrieve-version-from-maven-pom-xml-in-code
private String appVersion;
@Autowired
private String hostname;
@Value("${spring.datasource.url}")
private String dbUrl;
@Override
public void contribute(Info.Builder builder) {
log.info("AppVersionInfo: contribute ...");
builder.withDetail("app", "Cloud User API")
.withDetail("version", appVersion)
.withDetail("hostname",hostname)
.withDetail("dbUrl", dbUrl)
.withDetail("description", "This is a simple Spring Boot application to demonstrate the use of BigQuery in GCP.");
}
}
测试:
[gateman@manjaro-x13 gnome-shell]$ curl 127.0.0.1:8080/actuator/info
{"app":"Cloud User API","version":"0.0.1","hostname":"manjaro-x13","dbUrl":"jdbc:mysql://34.39.2.90:6033/demo_cloud_user?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true","description":"This is a simple Spring Boot application to demonstrate the use of BigQuery in GCP."}
[gateman@manjaro-x13 gnome-shell]$
本地是只能通过外网ip 来连接
让cloud Run service 也通过外网ip 来连接mysql
的确, 这个解决方案是可行的
我也测试过, 当部署service 到cloud run之后, 通过/info api返回的信息来看, service 的确能成功连接到mysql
[gateman@manjaro-x13 gnome-shell]$ curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" https://demo-cloud-user-7hq3m4pdya-nw.a.run.app/actuator/info
{"app":"Cloud User API","version":"0.0.1","hostname":"localhost","dbUrl":"jdbc:mysql://34.39.2.90:6033/demo_cloud_user?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true","description":"This is a simple Spring Boot application to demonstrate the use of BigQuery in GCP."}
[gateman@manjaro-x13 gnome-shell]$
但是这个方案有个缺点, 我家里电脑用外网ip 连接mysql 是没办法, 但是在GCP 上, 1个service 通过外网ip连接另1个service不是1个好选择
- 流量走了外网, 性能更慢, 收费更贵
- 安全问题
所以 Cloud Run的service 在生产上一般是要求用内网ip来访问内网的资源的
让cloud Run service 尝试通过内网ip 连接mysql
by default , 肯定是连不上的, 本文一开始讲过了
创建1个vpc connector
terraform 脚本:
resource "google_vpc_access_connector" "connector" {
name = "vpc-con"
network = google_compute_network.tf-vpc0.id # for the network where the connector will be created
machine_type = "e2-micro" # machine type for the connector
region = "europe-west2"
ip_cidr_range = "192.168.100.0/28" # means the connector will use created vms in this range
# should not overlap with the sub network's ip range
}
referring:
https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/vpc_access_connector
值得注意的参数
- network – 就是这个vpc connector 可以指向的vpc network了, 对于本文例子来讲就是 mysql 所在的vm 所在的 vpc subnet 所在的 vpc network
- machine_type – 明显这个vpc connector 背后还是要消耗一些24小时开机的vm, 如果是学习和测试目的, 选择最新规格的vm 类型就好, 如果是生产环境当让要看流量来选择了!
- ip_cidr_range – 因为每1个vpc connector 都是高可用的, 代表它实际上是1个vm group, 所以需要一些预留ip地址, 这个ip地址必须在对应的vpc-network内, 但不能与subnet 的ip range 重合。 而且必须用/28 结尾
在本文例子中
tf-vpc0 这个vm 已经有两个subnet
分别是:
tf-vpc0-subnet0: 192.168.0.0/24
tf-vpc0-subnet1: 192.168.1.0/24
所以这里的 ip_cidr_range 不能在 192.168.0.xxx ~ 192.168.1.xxx 内
我直接选择 192.168.100.0/28 了
创建成功后
UI 上见到的details 是这样的
可见, 最小都要占用2台 vm, 能自动扩展成3台, 当然这个2 和3 都是可以在terraform 里配置的
在Cloud run的deploy 脚本上加上vpc connector 的参数
cloud build的脚本:
steps:
- id: run maven package
name: maven:3.9.6-sapmachine-17 # https://hub.docker.com/_/maven
entrypoint: mvn
args: ['package', '-Dmaven.test.skip=true']
# https://cloud.google.com/build/docs/configuring-builds/substitute-variable-values
- id: build docker image
name: 'gcr.io/cloud-builders/docker'
args: ['build', '-t', 'europe-west2-docker.pkg.dev/$PROJECT_ID/my-docker-repo/${_APP_NAME}', '.']
- id: upload docker image to GAR
name: 'gcr.io/cloud-builders/docker'
args: [ 'push', 'europe-west2-docker.pkg.dev/$PROJECT_ID/my-docker-repo/${_APP_NAME}']
# deploy to Cloud run
- id: deploy image to cloud run
name: 'gcr.io/cloud-builders/gcloud'
args: ['run', 'deploy', 'demo-cloud-user',
'--image=europe-west2-docker.pkg.dev/$PROJECT_ID/my-docker-repo/${_APP_NAME}:${_APP_TAG}',
'--port=8080',
'--platform=managed',
'--region=europe-west2',
'--no-allow-unauthenticated',
'[email protected]',
'--key=projects/$PROJECT_ID/locations/europe-west2/keyRings/mykeyring/cryptoKeys/mycmek',
'--set-env-vars=APP_ENVIRONMENT=${_APP_ENV}',
'--vpc-connector=${_VPC_CONNECTOR}',
'--vpc-egress=all'
]
# https://stackoverflow.com/questions/68779751/error-publishing-source-code-from-cloud-build-to-a-bucket-using-triggers
logsBucket: gs://jason-hsbc_cloudbuild/logs/
options: # https://cloud.google.com/cloud-build/docs/build-config#options
logging: GCS_ONLY # or CLOUD_LOGGING_ONLY https://cloud.google.com/cloud-build/docs/build-config#logging
substitutions:
_APP_NAME: demo-cloud-user
_APP_TAG: latest
_APP_ENV: prod
_VPC_CONNECTOR: vpc-con
其中 --vpc-connector 就是 这个cloud run service 要使用的 vpc connector
至于 --vpc-egress=all 就是所有出去的流量都走这个vpc connector
测试:
部署成功:
[gateman@manjaro-x13 conf]$ curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" https://demo-cloud-user-7hq3m4pdya-nw.a.run.app/actuator/info
{"app":"Cloud User API","version":"0.0.1","hostname":"localhost","dbUrl":"jdbc:mysql://192.168.0.42:3306/demo_cloud_user?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true","description":"This is a simple Spring Boot application to demonstrate the use of BigQuery in GCP."}
[gateman@manjaro-x13 conf]$
[gateman@manjaro-x13 conf]$ curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" https://demo-cloud-user-7hq3m4pdya-nw.a.run.app/user/get/3
{"returnCode":0,"returnMsg":"User fetched successfully ...","data":{"id":3,"username":"华沉鱼","address":"湖北省十堰市"}}
[gateman@manjaro-x13 conf]$!
而且连接的数据库ip是内网ip
也能正确获得数据的返回