Calling an application outside cluster from a pod - gke-networking

There is a web service app running on a Compute Engine and a GKE cluster in the same network.
Is it possible for a pod in the cluster to call the web service app using internal IP address of web service app?
Your answer will be appreciated.
Thanks.

TL;DR
Yes it's possible.
Assuming that you are talking about the Internal IP address of your VM you will need to create a rule allowing traffic from pod address range to your VM.
Example
Assuming that:
There is a Compute Engine instance named: nginx and it's configured to run on port 80.
There is a Kubernetes Engine within the same network as your GCE instance.
You will need to check the pod ip address range of your GKE cluster. You can do it by either:
Cloud Console (Web UI)
$ gcloud container clusters describe CLUSTER-NAME --zone=ZONE | grep -i "clusterIpv4Cidr"
The firewall rule could be created by either:
Cloud Console (Web UI)
gcloud command like below:
gcloud compute --project=PROJECT-ID firewall-rules create pod-to-vm \
--direction=INGRESS --priority=1000 --network=default \
--action=ALLOW --rules=tcp:80 --source-ranges=clusterIpv4Cidr \
--target-tags=pod-traffic
Disclaimer!
Enter the value from last command (describe cluster) in the place of clusterIpv4Cidr
You will need to add pod-traffic to your VM's network tags!
After that you can spawn a pod and check if you can communicate with your VM:
$ kubectl run -it ubuntu --image=ubuntu -- /bin/bash
$ apt update && apt install -y curl dnsutils
You can communicate with your VM with GKE pods by either:
IP address of your VM:
root#ubuntu:/# curl IP_ADDRESS
REDACTED
<p><em>Thank you for using nginx.</em></p>
REDACTED
Name of your VM (nginx):
root#ubuntu:/# curl nginx
REDACTED
<p><em>Thank you for using nginx.</em></p>
REDACTED
You can also check if the name is correctly resolved by running:
root#ubuntu:/# nslookup nginx
Server: DNS-SERVER-IP
Address: DNS-SERVER-IP#53
Non-authoritative answer:
Name: nginx.c.PROJECT_ID.internal
Address: IP_ADDRESS
Additional resources:
Stackoverflow.com: Unable to connect from gke to gce

Related

How to access NodePort in Minikube with docker driver?

I launched minikube with the docker driver on a remote machine and I have used a nodePort service for a particular pod. I believe nodePort exposes the port on the minikube docker container. On doing minikube IP it gave me the IP of the docker container in which minikube runs. How can I port map the port from the minnikube container to the host port so that I can access it remotely. A different approach would other than using driver=none or restarting minikube is appreciated as I do not want to restart my spinnaker cluster.
There is a minikube service <SERVICE_NAME> --url command which will give you a url where you can access the service. In order to open the exposed service, the minikube service <SERVICE_NAME> command can be used:
$ minikube service example-minikube
Opening kubernetes service default/hello-minikube in default browser...
This command will open the specified service in your default browser.
There is also a --url option for printing the url of the service which is what gets opened in the browser:
$ minikube service example-minikube --url
http://192.168.99.100:31167
You can run minikube service list to get list of all available services with their corresponding URL's. Also make sure the service points to correct pod by using correct selector.
Try also to execute command:
ssh -i ssh -i ~/.minikube/machines/minikube/id_rsa docker#$(minikube ip) -L *:30000:0.0.0.0:30000
Take a look: minikube-service-port-forward, expose-port-minikube, minikube-service-documentation.

Add a route to Docker network macvlan to connect on both local and VPN

My aim is that the docker container gets an IP different from server IP it is hosted on AND is reachable from VPN client
My server hosting docker config:
$ sudo docker -v
Docker version 19.03.6, build 369ce74a3c
$ sudo docker-compose -v
docker-compose version 1.17.1, build unknown
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 18.04.1 LTS
Release: 18.04
Codename: bionic
The server is connected to a network on 192.168.0.0/24 with gateway on 192.168.0.10.
And I have another server with OpenVPN with ips 192.168.0.150 and 12.20.0.1 (for VPN).
Every computer connected in remote to the VPN gets an ip on 12.20.0.0/24 network
Previously, I used an Ubuntu VM on VirtualBox and I added a route on each VM to be accessible from VPN
ip route add 12.20.0.0/24 via 192.168.0.150
This worked!
Now I'm using docker to replace my VM
To get a different IP from server on 192.168.0.0/24 network
I created a docker network macvlan:
sudo docker network create -d macvlan -o parent=eno1 --subnet 192.168.0.0/24 --gateway 192.168.0.10 publicNet
Then I create a container test:
sudo docker run --rm -dit --privileged -network publicNet --name my-macvlan-alpine --ip="192.168.0.48" alpine:latest ash
(I use privileged to add a route, better idea?)
Now I try to ping (ping 192.168.0.48) my container from two locations:
From another server on 192.168.0.0/24 network OK
From a client of the VPN: KO
So I thought I needed to add the route I added in my VM
$ sudo docker exec -it my-macvlan-alpine ash -c "ip route add 12.20.0.0/24 via 192.168.0.150 && ip route"
default via 192.168.0.10 dev eth0
12.20.0.0/24 via 192.168.0.150 dev eth0
192.168.0.0/24 dev eth0 scope link src 192.168.0.48
Still, I can't ping from my VPN client computer
What am I doing wrong?
Thanks,

I can't get a shell from localhost to Pod

From Pod to localhost, ssh works well. And ping also works well with each other.
There is centos7 in Pod. Also, openssh-server is installed in Pod. But there is always an error.
kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE
hadoop-master-pod 1/1 Running 0 39m 10.244.9.25 slave10 <none>
hadoop-secondary-pod 1/1 Running 0 48m 10.244.11.11 slave12 <none>
ssh 10.244.9.25
ssh: connect to host 10.244.9.25 port 22: Connection refused
You should be able to connect using kubectl exec -it hadoop-master-pod -- /bin/bash
Then You can check if your pod in listening on port 22 for 0.0.0.0
Check the iptables if there is nothing blocked.
Make sure openssh is running and on which port it's running.
10.244.9.25 IP is an internal IP address given to pod by Kubernetes ( you can read more about Kubernetes networking model here ) to use inside Kubernets cluster so you won't be able to SSH or even to ping to these IPs from outside the cluster. In other words the network containing 10.244.9.25 is like a private network inside the K8 cluster and your host machine (localhost) is on different network.
If you want to get into the container for example in here you can use kubectl exec -it hadoop-master-pod -- /bin/bash or /bin/sh depending on the shell installed in the container and you can do anything that you tried to do by SSH into the pod.
If you really want to SSH into the pod from localhost (outside the cluster) you can write a Kubernetes Service probably exposing over NodePort which will expose the 22 (default port of SSH) to outside via NodePort.

docker-machine, create and run a nginx container is not exposing port 80

From this article it was really easy to "docker-machine create" a VM host on google compute engine. My problem is that when using the ip(docker-machine NameOfVM) to access a running nginx container it does not responde.
I can see that nginx is running, when I SSH into the VM and run "curl localhost".
I can ping the VM but curl or browser is not responding.
Do you know what I am missing?
ifconfig shows a docker0 adapter and a eth0.
Do I have to configure docker any further? As I understand, docker is not running any boot2docker/VM's on a linux machine?
Thanks
You may read firewall section of the Google Compute Engine docs to configure your firewall:
You can also create a firewall rule that allows HTTP traffic from anywhere to all instances on the example-network network. Execute the following:
$ gcloud compute firewall-rules create web --network example-network --allow tcp:80`

How to get the IP address of the docker host from inside a docker container [duplicate]

This question already has answers here:
From inside of a Docker container, how do I connect to the localhost of the machine?
(41 answers)
Closed 10 months ago.
As the title says, I need to be able to retrieve the IP address the docker hosts and the portmaps from the host to the container, and doing that inside of the container.
/sbin/ip route|awk '/default/ { print $3 }'
As #MichaelNeale noticed, there is no sense to use this method in Dockerfile (except when we need this IP during build time only), because this IP will be hardcoded during build time.
As of version 18.03, you can use host.docker.internal as the host's IP.
Works in Docker for Mac, Docker for Windows, and perhaps other platforms as well.
This is an update from the Mac-specific docker.for.mac.localhost, available since version 17.06, and docker.for.mac.host.internal, available since version 17.12, which may also still work on that platform.
Note, as in the Mac and Windows documentation, this is for development purposes only.
For example, I have environment variables set on my host:
MONGO_SERVER=host.docker.internal
In my docker-compose.yml file, I have this:
version: '3'
services:
api:
build: ./api
volumes:
- ./api:/usr/src/app:ro
ports:
- "8000"
environment:
- MONGO_SERVER
command: /usr/local/bin/gunicorn -c /usr/src/app/gunicorn_config.py -w 1 -b :8000 wsgi
Update: On Docker for Mac, as of version 18.03, you can use host.docker.internal as the host's IP. See aljabear's answer. For prior versions of Docker for Mac the following answer may still be useful:
On Docker for Mac the docker0 bridge does not exist, so other answers here may not work. All outgoing traffic however, is routed through your parent host, so as long as you try to connect to an IP it recognizes as itself (and the docker container doesn't think is itself) you should be able to connect. For example if you run this from the parent machine run:
ipconfig getifaddr en0
This should show you the IP of your Mac on its current network and your docker container should be able to connect to this address as well. This is of course a pain if this IP address ever changes, but you can add a custom loopback IP to your Mac that the container doesn't think is itself by doing something like this on the parent machine:
sudo ifconfig lo0 alias 192.168.46.49
You can then test the connection from within the docker container with telnet. In my case I wanted to connect to a remote xdebug server:
telnet 192.168.46.49 9000
Now when traffic comes into your Mac addressed for 192.168.46.49 (and all the traffic leaving your container does go through your Mac) your Mac will assume that IP is itself. When you are finish using this IP, you can remove the loopback alias like this:
sudo ifconfig lo0 -alias 192.168.46.49
One thing to be careful about is that the docker container won't send traffic to the parent host if it thinks the traffic's destination is itself. So check the loopback interface inside the container if you have trouble:
sudo ip addr show lo
In my case, this showed inet 127.0.0.1/8 which means I couldn't use any IPs in the 127.* range. That's why I used 192.168.* in the example above. Make sure the IP you use doesn't conflict with something on your own network.
AFAIK, in the case of Docker for Linux (standard distribution), the IP address of the host will always be 172.17.0.1 (on the main network of docker, see comments to learn more).
The easiest way to get it is via ifconfig (interface docker0) from the host:
ifconfig
From inside a docker, the following command from a docker: ip -4 route show default | cut -d" " -f3
You can run it quickly in a docker with the following command line:
# 1. Run an ubuntu docker
# 2. Updates dependencies (quietly)
# 3. Install ip package (quietly)
# 4. Shows (nicely) the ip of the host
# 5. Removes the docker (thanks to `--rm` arg)
docker run -it --rm ubuntu:22.04 bash -c "apt-get update > /dev/null && apt-get install iproute2 -y > /dev/null && ip -4 route show default | cut -d' ' -f3"
For those running Docker in AWS, the instance meta-data for the host is still available from inside the container.
curl http://169.254.169.254/latest/meta-data/local-ipv4
For example:
$ docker run alpine /bin/sh -c "apk update ; apk add curl ; curl -s http://169.254.169.254/latest/meta-data/local-ipv4 ; echo"
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/community/x86_64/APKINDEX.tar.gz
v3.3.1-119-gb247c0a [http://dl-cdn.alpinelinux.org/alpine/v3.3/main]
v3.3.1-59-g48b0368 [http://dl-cdn.alpinelinux.org/alpine/v3.3/community]
OK: 5855 distinct packages available
(1/4) Installing openssl (1.0.2g-r0)
(2/4) Installing ca-certificates (20160104-r2)
(3/4) Installing libssh2 (1.6.0-r1)
(4/4) Installing curl (7.47.0-r0)
Executing busybox-1.24.1-r7.trigger
Executing ca-certificates-20160104-r2.trigger
OK: 7 MiB in 15 packages
172.31.27.238
$ ifconfig eth0 | grep -oP 'inet addr:\K\S+'
172.31.27.238
The only way is passing the host information as environment when you create a container
run --env <key>=<value>
The --add-host could be a more cleaner solution (but without the port part, only the host can be handled with this solution). So, in your docker run command, do something like:
docker run --add-host dockerhost:`/sbin/ip route|awk '/default/ { print $3}'` [my container]
(From https://stackoverflow.com/a/26864854/127400 )
docker network inspect bridge -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}'
It's possible to retrieve it using docker network inspect
The standard best practice for most apps looking to do this automatically is: you don't. Instead you have the person running the container inject an external hostname/ip address as configuration, e.g. as an environment variable or config file. Allowing the user to inject this gives you the most portable design.
Why would this be so difficult? Because containers will, by design, isolate the application from the host environment. The network is namespaced to just that container by default, and details of the host are protected from the process running inside the container which may not be fully trusted.
There are different options depending on your specific situation:
If your container is running with host networking, then you can look at the routing table on the host directly to see the default route out. From this question the following works for me e.g.:
ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'
An example showing this with host networking in a container looks like:
docker run --rm --net host busybox /bin/sh -c \
"ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'"
For current versions of Docker Desktop, they injected a DNS entry into the embedded VM:
getent hosts host.docker.internal | awk '{print $1}'
With the 20.10 release, the host.docker.internal alias can also work on Linux if you run your containers with an extra option:
docker run --add-host host.docker.internal:host-gateway ...
If you are running in a cloud environment, you can check the metadata service from the cloud provider, e.g. the AWS one:
curl http://169.254.169.254/latest/meta-data/local-ipv4
If you want your external/internet address, you can query a remote service like:
curl ifconfig.co
Each of these have limitations and only work in specific scenarios. The most portable option is still to run your container with the IP address injected as a configuration, e.g. here's an option running the earlier ip command on the host and injecting it as an environment variable:
export HOST_IP=$(ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p')
docker run --rm -e HOST_IP busybox printenv HOST_IP
TLDR for Mac and Windows
docker run -it --rm alpine nslookup host.docker.internal
... prints the host's IP address ...
nslookup: can't resolve '(null)': Name does not resolve
Name: host.docker.internal
Address 1: 192.168.65.2
Details
On Mac and Windows, you can use the special DNS name host.docker.internal.
The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker Desktop for Mac.
If you want real IP address (not a bridge IP) on Windows and you have docker 18.03 (or more recent) do the following:
Run bash on container from host where image name is nginx (works on Alpine Linux distribution):
docker run -it nginx /bin/ash
Then run inside container
/ # nslookup host.docker.internal
Name: host.docker.internal
Address 1: 192.168.65.2
192.168.65.2 is the host's IP - not the bridge IP like in spinus accepted answer.
I am using here host.docker.internal:
The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker for Windows.
In linux you can run
HOST_IP=`hostname -I | awk '{print $1}'`
In macOS your host machine is not the Docker host. Docker will install it's host OS in VirtualBox.
HOST_IP=`docker run busybox ping -c 1 docker.for.mac.localhost | awk 'FNR==2 {print $4}' | sed s'/.$//'`
I have Ubuntu 16.03. For me
docker run --add-host dockerhost:`/sbin/ip route|awk '/default/ { print $3}'` [image]
does NOT work (wrong ip was generating)
My working solution was that:
docker run --add-host dockerhost:`docker network inspect --format='{{range .IPAM.Config}}{{.Gateway}}{{end}}' bridge` [image]
Docker for Mac
I want to connect from a container to a service on the host
The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host.
The gateway is also reachable as gateway.docker.internal.
https://docs.docker.com/docker-for-mac/networking/#use-cases-and-workarounds
If you enabled the docker remote API (via -Htcp://0.0.0.0:4243 for instance) and know the host machine's hostname or IP address this can be done with a lot of bash.
Within my container's user's bashrc:
export hostIP=$(ip r | awk '/default/{print $3}')
export containerID=$(awk -F/ '/docker/{print $NF;exit;}' /proc/self/cgroup)
export proxyPort=$(
curl -s http://$hostIP:4243/containers/$containerID/json |
node -pe 'JSON.parse(require("fs").readFileSync("/dev/stdin").toString()).NetworkSettings.Ports["DESIRED_PORT/tcp"][0].HostPort'
)
The second line grabs the container ID from your local /proc/self/cgroup file.
Third line curls out to the host machine (assuming you're using 4243 as docker's port) then uses node to parse the returned JSON for the DESIRED_PORT.
My solution:
docker run --net=host
then in docker container:
hostname -I | awk '{print $1}'
Here is another option for those running Docker in AWS. This option avoids having using apk to add the curl package and saves the precious 7mb of space. Use the built-in wget (part of the monolithic BusyBox binary):
wget -q -O - http://169.254.169.254/latest/meta-data/local-ipv4
use hostname -I command on the terminal
Try this:
docker run --rm -i --net=host alpine ifconfig
So... if you are running your containers using a Rancher server, Rancher v1.6 (not sure if 2.0 has this) containers have access to http://rancher-metadata/ which has a lot of useful information.
From inside the container the IP address can be found here:
curl http://rancher-metadata/latest/self/host/agent_ip
For more details see:
https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-service/
This is a minimalistic implementation in Node.js for who is running the host on AWS EC2 instances, using the afore mentioned EC2 Metadata instance
const cp = require('child_process');
const ec2 = function (callback) {
const URL = 'http://169.254.169.254/latest/meta-data/local-ipv4';
// we make it silent and timeout to 1 sec
const args = [URL, '-s', '--max-time', '1'];
const opts = {};
cp.execFile('curl', args, opts, (error, stdout) => {
if (error) return callback(new Error('ec2 ip error'));
else return callback(null, stdout);
})
.on('error', (error) => callback(new Error('ec2 ip error')));
}//ec2
and used as
ec2(function(err, ip) {
if(err) console.log(err)
else console.log(ip);
})
If you are running a Windows container on a Service Fabric cluster, the host's IP address is available via the environment variable Fabric_NodeIPOrFQDN. Service Fabric environment variables
Here is how I do it. In this case, it adds a hosts entry into /etc/hosts within the docker image pointing taurus-host to my local machine IP: :
TAURUS_HOST=`ipconfig getifaddr en0`
docker run -it --rm -e MY_ENVIRONMENT='local' --add-host "taurus-host:${TAURUS_HOST}" ...
Then, from within Docker container, script can use host name taurus-host to get out to my local machine which hosts the docker container.
Maybe the container I've created is useful as well https://github.com/qoomon/docker-host
You can simply use container name dns to access host system e.g. curl http://dockerhost:9200, so no need to hassle with any IP address.
The solution I use is based on a "server" that returns the external address of the Docker host when it receives a http request.
On the "server":
1) Start jwilder/nginx-proxy
# docker run -d -p <external server port>:80 -v /var/run/docker.sock:/tmp/docker.sock:ro jwilder/nginx-proxy
2) Start ipify container
# docker run -e VIRTUAL_HOST=<external server name/address> --detach --name ipify osixia/ipify-api:0.1.0
Now when a container sends a http request to the server, e.g.
# curl http://<external server name/address>:<external server port>
the IP address of the Docker host is returned by ipify via http header "X-Forwarded-For"
Example (ipify server has name "ipify.example.com" and runs on port 80, docker host has IP 10.20.30.40):
# docker run -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock:ro jwilder/nginx-proxy
# docker run -e VIRTUAL_HOST=ipify.example.com --detach --name ipify osixia/ipify-api:0.1.0
Inside the container you can now call:
# curl http://ipify.example.com
10.20.30.40
On Ubuntu, hostname command can be used with the following options:
-i, --ip-address addresses for the host name
-I, --all-ip-addresses all addresses for the host
For example:
$ hostname -i
172.17.0.2
To assign to the variable, the following one-liner can be used:
IP=$(hostname -i)
Another approach is based on traceroute and it's working on a Linux host for me, e.g. in a container based on Alpine:
traceroute -n 8.8.8.8 -m 4 -w 1 | awk '$1~/\d/&&$2!~/^172\./{print$2}' | head -1
It takes a moment, but lists the first hop's IP that does not start with 172. If there is no successful response, try increasing the limit on the tested hops using -m 4 argument.
With https://docs.docker.com/machine/install-machine/
a) $ docker-machine ip
b) Get the IP address of one or more machines.
$ docker-machine ip host_name
$ docker-machine ip host_name1 host_name2

Resources