I have a NET Core Console Application which has a socket binded to a port.
I have dockerized this application and i am trying to expose the binded port.The program shows its output correctly when i use docker attach [instance] .However when trying to connect with Telnet i get the error:
Error
$ telnet 127.0.0.1 20001
Connecting To 127.0.0.1...Could not open connection to the host, on port 8806: Connect failed
.NET Server
class Program {
public const int BUFFER_SIZE = 1024;
public const int EXPOSED_PORT = 20001;
public const string ADDRESS = "127.0.0.1";
public const int MAX_CONNECTIONS = 1;
public static ReadOnlyMemory<byte> CreateMessage(ReadOnlyMemory<byte>request) {
Memory<byte> response= Encoding.UTF8.GetBytes($"Response from Daemon:{DateTime.Now.ToString()}");
///------code------//
return response;
}
static async Task Main(string[] args) {
Memory<byte> buffer = ArrayPool<byte>.Shared.Rent(BUFFER_SIZE);
using (Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
serverSocket.Bind(new IPEndPoint(IPAddress.Parse(ADDRESS), EXPOSED_PORT));
Console.WriteLine($"Server started at {DateTime.Now.ToShortTimeString()} \r\nListening on port{EXPOSED_PORT}");
serverSocket.Listen(MAX_CONNECTIONS);
var client =await serverSocket.AcceptAsync();
while (true) {
int rxCount =await client.ReceiveAsync(buffer, SocketFlags.None);
if ((char) buffer.Span[0] == 'x'){
break;
}
await client.SendAsync(CreateMessage(buffer.Slice(0, rxCount)), SocketFlags.None);
}
}
ArrayPool<byte>.Shared.Return(buffer.ToArray());
}
}
Dockerfile
FROM microsoft/dotnet:latest
WORKDIR /app
COPY ./bin/Release/netcoreapp2.1/publish .
ENTRYPOINT [ "dotnet","DockerContainerDaemon.dll" ]
EXPOSE 20001
docker and build command script
dotnet build -c Release
dotnet publish
docker build --build-arg Port=20001 -t daemon .
docker stop inst1
docker rm inst1
docker run --name inst1 -p 20001:20001 -d daemon
Running docker -ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f675c3e502ad daemon "dotnet DockerContai…" 5 seconds ago Up 3 seconds 0.0.0.0:20001->20001/tcp inst1
P.S As someone pointed out i tried exposing with both 127.0.0.1 and 0.0.0.0 from the .NET Application. to no avail.
Try to bind the application to 0.0.0.0 instead of 127.0.0.1. This will solve your problem.
Related
I am trying to access the grpc server which exposes 9000 port and is running as docker container.
I am using .net core client to connect to the server.It works perfectly fine when GRPC server is not running as a docker container.
I have tried using both the "localhost","dockerconatiner-ip" while creating the channel from client.I am running the grpc server on "0.0.0.0"and port 9000.
docker commands:
docker run -p 9000:9000 -a stdin -a stdout -it
Error:
Status(StatusCode=Unavailable, Detail="DNS resolution failed")
dockerfile:
FROM mcr.microsoft.com/dotnet/core/runtime:3.0
COPY Sample/bin/Release/netcoreapp3.0/publish/ app/
WORKDIR /app
EXPOSE 9000
ENTRYPOINT ["dotnet", "Sample.dll"]
Service Main:
static void Main(string[] args)
{
try
{
Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "DEBUG");
const int Port = 9000;
Server server = new Server
{
Ports = { new ServerPort("0.0.0.0", 9000, ServerCredentials.Insecure) },
Services = { BindService(new TestService()) }
};
server.Start();
Console.WriteLine("starting server");
Console.WriteLine("Press any key to shut down");
Console.ReadKey();
server.ShutdownAsync().Wait();
Console.WriteLine("Grpc Server stopped");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Test service has a method to print received text to console.
I am learning how to run my .net core web applications on docker (on windows host) with SSL. I started with the basic application that .net core gives by doing "dotnet new mvc".
Then I moved ahead and modified the code inside Program.cs to listen only on port 443.
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(options =>
{
options.Listen(IPAddress.Any, 443, listenOptions =>
{
listenOptions.UseHttps("test.com.pfx", "1234");
});
})
.Build();
}
I created s self signed certificate and mentioned the password. Please ignore the way the password is exposed as I am still doing this as a POC.
Then I modified my dockerfile as:
FROM microsoft/dotnet
WORKDIR /app
COPY bin/Debug/netcoreapp2.0/publish .
EXPOSE 443
ENTRYPOINT ["dotnet", "dotnetssl.dll"]
Now If I build and run the image with:
docker build -t httpssample .
docker run -it -p 443:443 httpssample
I am not able to access the website with the URL https://localhost , also I get below lines printed in the console:
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
No XML encryptor configured. Key {9f9e447d-d766-4a7d-9413-03466512b7a9} may be persisted to storage in unencrypted form.
warn: Microsoft.AspNetCore.Server.Kestrel[0]
Unable to bind to http://localhost:5000 on the IPv6 loopback interface: 'Error -99 EADDRNOTAVAIL address not available'.
Hosting environment: Production
Content root path: /app
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
set .env like the followings about Server address.
APP_URL=http://localhost:8000
APP_DOMAIN=localhost
I am using apache2 (docker container) as web server.
under this condition, to test with dusk, started up selenium/standalone-chrome as another container.
docker run -p 4444:4444 --name selenium --link apache2:apache2 -d selenium/standalone-chrome
to confirm the connection between docker containers,
used the following commands
docker exec -it selenium bash,
cat /etc/hosts/
result was
172.17.0.6 apache2 a1c15575e4c8
also confirmed ping apache2 from selenium container.
but from here, couldn't do dusk test using following command.
when I check the browser response, there was no contents.
docker exec apache2 php artisan dusk
I think setting is wrong. but can't notice it.
could you help?
the following is php source code.
DuskTestCase.php
abstract class DuskTestCase extends BaseTestCase
{
use CreatesApplication;
/**
* Prepare for Dusk test execution.
*
* #beforeClass
* #return void
*/
public static function prepare()
{
static::startChromeDriver();
}
/**
* Create the RemoteWebDriver instance.
*
* #return \Facebook\WebDriver\Remote\RemoteWebDriver
*/
protected function driver()
{
$options = (new ChromeOptions)->addArguments([
'--disable-gpu',
'--headless'
]);
return RemoteWebDriver::create(
'http://selenium:4444/wd/hub', DesiredCapabilities::chrome()->setCapability(
ChromeOptions::CAPABILITY, $options
)
);
}
}
ExampleTest.php
class ExampleTest extends DuskTestCase
{
public function testBasicExample()
{
$this->browse(function (Browser $browser) {
print_r($browser->visit('/')->resolver->elements);exit;
$browser->visit('/')
->assertSee('login');
});
}
}
I'm running aerospike server in docker.
$ docker run -d --name aerospike aerospike/aerospike-server
0ad3b2df67bd17f896e87ed119758d9af7fcdd9b82a8632828e01072e2c5673f
It is started successfully.
$docker ps
CONTAINER ID IMAGE COMMAND
CREATED STATUS PORTS NAMES
0ad3b2df67bd aerospike/aerospike-server "/entrypoint.sh asd"
4 seconds ago Up 2 seconds 3000-3003/tcp aerospike
I found the ip address of docker using below command.
$ docker inspect -f '{{.NetworkSettings.IPAddress }}' aerospike
172.17.0.2
When I trying to connect to aql using the below command, it is successful as well.
$ docker run -it aerospike/aerospike-tools aql -h $(docker inspect -f
'{{.NetworkSettings.IPAddress }}' aerospike)
Aerospike Query Client
Version 3.15.0.3
C Client Version 4.2.0
Copyright 2012-2017 Aerospike. All rights reserved.
aql> select * from test.person
0 rows in set (0.002 secs)
Now I am trying to connect to the aerospike server in docker using java client in host machine.
public class AerospikeDemo {
public static void main(String []args) {
AerospikeClient client = new AerospikeClient("172.17.0.2", 3000);
Key key = new Key("test", "demo", "putgetkey");
//Key key2 = new Key("1", "2", "3");
Bin bin1 = new Bin("bin1", "value1");
Bin bin2 = new Bin("bin2", "value2");
Bin bin3 = new Bin("bin2", "value3");
// Write a record
client.put(null, key, bin1, bin2, bin3);
// Read a record
Record record = client.get(null, key);
System.out.println("record is "+ record);
System.out.println("record bins is " + record.bins);
client.close();
}
}
When I run the above program, I'm getting below error -
objc[3446]: Class JavaLaunchHelper is implemented in both
/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/bin/java (0x10f7b14c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x10f8794e0). One of the two will be used. Which one is undefined.
Exception in thread "main" com.aerospike.client.AerospikeException$Connection:
Error Code 11: Failed to connect to host(s): 172.17.0.2 3000 Error Code 11: java.net.SocketTimeoutException: connect timed out
at com.aerospike.client.cluster.Cluster.seedNodes(Cluster.java:413)
at com.aerospike.client.cluster.Cluster.tend(Cluster.java:306)
at com.aerospike.client.cluster.Cluster.waitTillStabilized(Cluster.java:271)
at com.aerospike.client.cluster.Cluster.initTendThread(Cluster.java:181)
at com.aerospike.client.AerospikeClient.<init>(AerospikeClient.java:210)
at com.aerospike.client.AerospikeClient.<init>(AerospikeClient.java:151)
at com.demo.aerospike.AerospikeDemo.main(AerospikeDemo.java:12)
I've tried both AerospikeClient("172.17.0.2", 3000) and AerospikeClient("localhost", 3000)
I see in the Dockerfile the port 3000 is exposed to the host but I'm not sure why I'm not able to use the aerospike server in the docker.
The IP 172.17.0.2 is only accessible within Docker (therefore you can use another container to connect). In case you want to connect from your host you need to map the respective port.
docker run -d --name aerospike -p 3000:3000 aerospike/aerospike-server
Afterwards you can use:
AerospikeClient client = new AerospikeClient("localhost", 3000);
I have a very simple application. Here is the code:
package main
import (
"fmt"
"math/rand"
"time"
"net/http"
"encoding/base64"
"encoding/json"
)
type Message struct {
Text string `json:"text"`
}
var cookieQuotes = []string{
// Skipped all the stuff
}
const COOKIE_NAME = "your_cookie"
func main() {
http.HandleFunc("/set_cookie", setCookie)
http.HandleFunc("/get_cookie", getCookie)
http.Handle("/favicon.ico", http.NotFoundHandler())
http.ListenAndServe(":8080", nil)
}
func setCookie(w http.ResponseWriter, r *http.Request) {
quote := getRandomCookieQuote()
encQuote := base64.StdEncoding.EncodeToString([]byte(quote))
http.SetCookie(w, &http.Cookie{
Name: COOKIE_NAME,
Value: encQuote,
})
}
func getCookie(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(COOKIE_NAME)
if err != nil {
fmt.Fprintln(w, "Cannot get the cookie")
}
message, _ := base64.StdEncoding.DecodeString(cookie.Value)
msg := Message{Text:string(message)}
fmt.Println(msg.Text)
respBody, err := json.Marshal(msg)
fmt.Println(string(respBody))
if err != nil {
fmt.Println("Cannot marshall JSON")
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, string(respBody))
}
func getRandomCookieQuote() string {
source := rand.NewSource(time.Now().UnixNano())
random := rand.New(source)
i := random.Intn(len(cookieQuotes))
return cookieQuotes[i]
}
It was tested locally, and, also I've tried to run a docker container with it on my machine (Ubuntu) and it was working perfectly. But I want to run it on Virtual Machine (I use Oracle Virtual Box).
So, I have installed docker-machine:
docker-machine version 0.12.2, build 9371605
After that, I've switched to it, like it was recommended in official documentation like this:
eval "$(docker-machine env default)"
So I can do now from a perspective of that machine.
Also I've tried to run ngnix from the documentation example:
docker run -d -p 8000:80 nginx
curl $(docker-machine ip default):8000
And I get the result, I can get to ngnix welcome page by accessing my docker machine ip-address which could be accessed by command:
docker-machine ip default
But when I try to run my own docker image, I could not do this. When I try to access it, I get:
curl $(docker-machine ip default):8080
curl: (7) Failed to connect to 192.168.99.100 port 8080: Connection refused
Also I've tried to skip a port, to add protocol (http, and even https for the sake of luck) - nothing works.
Maybe, something wrong with my Dockerfile?
# Go experiments with cookies
FROM golang:1.8-onbuild
MAINTAINER vasyania2#gmail.com
Could you help me please?
This command maps port 8080 from your docker host to port 80 of your container:
docker run -d -p 8080:80 cookie-app
This instruction tells your go application to listen on port 8080, inside the container:
http.ListenAndServe(":8080", nil)
You have a port mismatch in those above lines, your application is not listening on the port you are forwarding to.
To connect to port 8080 of your container, you can run the following:
docker run -d -p 8080:8080 cookie-app