<p>I am facing issue. I am trying to access Kubernetes API from Docker Container (Created .NetCore). I am getting Error Message <strong>"Connection Refused"</strong>.</p>

<p>Can anyone help?
I shall be thankful.</p>

<pre><code>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();
}
</code></pre>

<p>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 <code>kubernetes</code>, so the connection url would be <code>https://kubernetes/</code>.</p>

<p>If you are running the docker container locally and want to use the <code>kubectl proxy</code> 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: <code>docker run --net=host</code>. This only works if you are using linux, on MacOS or Windows a virtual machine is used to host the docker containers and <code>localhost</code> is then the VM, not your desktop. You would then use one of the special host names <code>docker.for.mac.host.internal</code> or <code>docker.for.win.localhost</code>, 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.</p>

<p>BTW: If you are using kubectl-proxy, it will automatically authenticate the requests and there is no need to add a bearer token.</p>
