I am facing issue. I am trying to access Kubernetes API from Docker Container (Created .NetCore). I am getting Error Message "Connection Refused".
Can anyone help? I shall be thankful.
using (HttpClient client = new HttpClient()) {
var request_json = JsonConvert.SerializeObject(obj).ToString();
var content = new StringContent(request_json, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Token");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Connection.Add("close");
var result = await client.PostAsync("http://127.0.0.1:8001/apis/batch/v1/namespaces/default", content);
var result_string = await result.Content.ReadAsStringAsync()`enter code here`;
return result_string.ToString();
}
If your docker container is running inside a kubernetes cluster, you can access the kubernetes API through a service. In the default namespace the service is already provided as kubernetes
, so the connection url would be https://kubernetes/
.
If you are running the docker container locally and want to use the kubectl proxy
to access the kubernetes api the docker container must be running without network isolation in order to be able to access the local proxy port: docker run --net=host
. This only works if you are using linux, on MacOS or Windows a virtual machine is used to host the docker containers and localhost
is then the VM, not your desktop. You would then use one of the special host names docker.for.mac.host.internal
or docker.for.win.localhost
, but you will need to launch the kubectl-proxy accordingly to listen not only on the loopback network interface, since the request will come from the docker-vm, which is external.
BTW: If you are using kubectl-proxy, it will automatically authenticate the requests and there is no need to add a bearer token.