我們知道Openshift容器化平台中, POD有自己的IP地址, 但是它只能在集羣的內部可用. 那如果我要從其他物理計算機通過網絡訪問容器內的MySQL怎麼辦呢?
我想到了Router, 但是, Router 只支持HTTP協議的轉發, 我們要使用TCP. 因此, NodePort出場了!
通過NodePort
這種方式適合長期使用, 對外提供
先看看有DC的名稱
➜ oc get dc
NAME REVISION DESIRED CURRENT TRIGGERED BY
hello-microservice 1 1 1 config,image(hello-microservice:latest)
mysql-57-centos7 11 1 1 config,image(mysql-57-centos7:latest)
nodejs-ex 1 1 1 config,image(nodejs-ex:latest)
mysql-57-centos7 是我們需要的
暴露指定DC, 暴露類型為 LoadBalancer, 暴露的名稱為
oc expose dc mysql-57-centos7 --type=LoadBalancer --name=mysql-ingress
導出
➜ oc export svc mysql-ingress
apiVersion: v1
kind: Service
metadata:
creationTimestamp: null
labels:
app: mysql-57-centos7
name: mysql-ingress
spec:
deprecatedPublicIPs:
- 172.29.208.121
externalIPs:
- 172.29.208.121
ports:
- nodePort: 32621
port: 3306
protocol: TCP
targetPort: 3306
selector:
app: mysql-57-centos7
deploymentconfig: mysql-57-centos7
sessionAffinity: None
type: LoadBalancer
status:
loadBalancer: {}
在導出的配置中, 我們看到 spec.ports.nodePort 為 32621, 這個端口就是我們可以從外部訪問MySQL的目標端口.
登錄MySQL測試連通性
➜ mysql --user=data --password=data --host=$(minishift ip) --port=32621
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 13
Server version: 5.7.16 MySQL Community Server (GPL)
Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
OK, 看起來沒有問題.
注意: 注意分配合適的登錄權限. 比如:
ERROR 1045 (28000): Access denied for user 'data'@'172.17.0.1' (using password: NO)
因此需要給登錄客户端所在的IP地址分配權限:
CREATE USER 'data'@'172.17.0.1' IDENTIFIED BY 'data';
GRANT ALL PRIVILEGES ON *.* TO 'data'@'172.17.0.1';
FLUSH PRIVILEGES;
通過端口轉發
端口轉發可以通過你的物理機器所在的網絡連接到POD,多用於開發測試環境
開啓端口轉發
➜ oc port-forward mysql-57-centos7-11-2wfs4 10001:3306
Forwarding from 127.0.0.1:10001 -> 3306
Forwarding from [::1]:10001 -> 3306
Handling connection for 10001
MySQL連接測試
➜ mysql -udata --password=data --host=127.0.0.1 --port=10001
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.7.16 MySQL Community Server (GPL)
Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
上述方法不限於MySQL這樣的應用, 各種基於TCP的應用都可以使用這兩種方式, 在合適的環境中使用.