k8s访问集群外独立的服务最好的方式是采用Endpoint方式(可以看作是将k8s集群之外的服务抽象为内部服务),以mysql服务为例:

创建mysql-endpoints.yaml

apiVersion: v1
kind: Endpoints
metadata:
name: mysql-test
namespace: default
subsets:
-addresses: -ip: 10.1.0.32 ports:
-port: 3306多个端口的话可以在此处列出

创建mysql-service.yaml

apiVersion: v1
kind: Service
metadata:
name: mysql-test
spec:
ports:
- port: 3306

测试连接数据库:

[root@LOC-XAN-PRO-032 run]# kubectl exec -it mysql-1225577607-rv8c1 sh
/data # ping mysql-test
PING mysql-test (10.254.121.162): 56 data bytes
^C
--- mysql-test ping statistics ---
11 packets transmitted, 0 packets received, 100% packet loss
/data # mysql -hmysql-test -ubill -ppass
ERROR 1045 (28000): Access denied for user 'bill'@'172.30.95.10' (using password: YES)
/data # mysql -hmysql-test -ulienhua -p123
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 5.5.52-MariaDB MariaDB Server

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| lienhua |
| test |
+--------------------+
3 rows in set (0.00

查看这个service

[root@LOC-XAN-PRO-032 mysql]# kubectl describe svc mysql-test
Name: mysql-test
Namespace: default
Labels: <none>
Annotations: <none>
Selector: <none>
Type: ClusterIP
IP: 10.254.121.162
Port: <unset> 3306/TCP
Endpoints: 10.1.0.32:3306
Session Affinity: None
Events: