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.