Service Fabric: Using Dynamically Assigned Port in Guest Executable

This is a continuation of my previous blog post where I demonstrated how to setup a node Express app in Service Fabric along side an .Net Core app. It turns out there is an undocumented way to use the dynamically assigned port for the service and use it in the within the guest executable.

Review of Current Method for Guest Executables:

From the current documentation on running guest executables they don’t mention any way for the guest executable to get the port allocated for the service instance. The work around was to hard-code the port in both the ServiceManifest.xml and also in the guest executable. This ensured the application would implicitly be listening on the port service fabric would forward traffic to. This worked but hard-coding is bad practice and more importantly this severely limited the use of guest executables because it only allowed running a single instance. If you tried to run multiple instances they would all be attempting to listen on the same port and there would be a conflict.

How to Use The Dynamically Assigned Port?

After poking around the local cluster files while I was searching for the redirected console log output I noticed there is a generated file:
ExpressPkg.Endpoints.txt as seen in the picture below:

This can be found in the application package deployed to the local cluster such as: `C:\SfDevCluster\Data\_App\_Node_0\ApplicationType_App0`

Inside that file you will find a semicolon separated list of values such as:


This matches the data from the corresponding ServiceManifest.xml:

`<Endpoint Name=”ExpressTypeEndpoint” Protocol=”http” Type=”Input” UriScheme=”http” />`

Notice that the port is added!

We can read this file, parse the text, and use the port value instead of our hard-coded value. Here is some sample code to achieve that:

Notice line 3 which uses array destructuring to extract value into constant named port. If you notice the next value is named ‘x’. I couldn’t find out what the purpose of that slot is.

Here is a quick video demonstrating what I explained above:


Since this isn’t documented and there are much better ways to give the guest executable the information about the port I assume this technique of directly reading the file is not officially supported. The contents or location of the file might change in the next version of the service fabric SDK so this is probably not a good choice for production, but currently it’s the only workaround I know of to run multiple instances of guest executables.

Let me know if you like this content and video. How is your experience with Service Fabric and Node?

Remember, all the code is available to try out yourself here: