mpc
mpc

Reputation: 89

Erlang Cowboy running two web servers on one machine using different ports

Newbie to erlang and cowboy. I am using some open source code which uses cowboy and listens to port 8080 to provide a ng-admin admin service.

I want to know if its possible for cowboy to also listen to port 80 to provide a users interface.

Any help and suggestions of where to start or any code snippets would be greatly appreciated.

Many Thanks,

MPC

Upvotes: 0

Views: 584

Answers (3)

ScReeChHB
ScReeChHB

Reputation: 1

Thank you for the above example. But unfortunately as is the example did not work for me.

I kept getting service "already_started" errors. I eventually figured out that I had to provide each listener its own unique name.

    NormalRoutes = cowboy_router:compile(...),
    AdminRoutes = cowboy_router:compile(...),
    {ok, _} = cowboy:start_clear(http_listener_name_1, [{port, 80}], #{
      env => #{dispatch => NormalRoutes}
    }),
    {ok, _} = cowboy:start_clear(http_listener_name_2, [{port, 8080}], #{
      env => #{dispatch => AdminRoutes}
    }).

cowboy:start_clear(3)

Hopefully that will help someone with the same problem I had.

Upvotes: 0

codeadict
codeadict

Reputation: 2753

According to my understanding of your question, you wan to have 2 servers running on different ports. You can call cowboy:start_clear/3 twice, with a different port and same or different routes. It is definitely doable but as mentioned above is more recommended to use namespace routes to separate applications (like /foo/123 and /admin/foo/123) instead of different ports if they use the same protocol (http in this case). In case you still need the tow servers, it will be something like:

    NormalRoutes = cowboy_router:compile(...),
    AdminRoutes = cowboy_router:compile(...),
    {ok, _} = cowboy:start_clear(http, [{port, 80}], #{
      env => #{dispatch => NormalRoutes}
    }),
    {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{
      env => #{dispatch => AdminRoutes}
    }).

Upvotes: 2

Ming L.
Ming L.

Reputation: 401

My understanding of the question is whether you can start two cowboy servers in the same erlang VM. Two servers listen to two different ports. Yes you can do that. Basically you compile their own routes and bind to 8080 and 80 port when you call cowboy:start_clear.

The question is if this practice makes sense. I would suggest if you can use routes to separate two applications instead of at port level/individual web server.

Upvotes: 0

Related Questions