Ric
Ric

Reputation: 211

Docker port forwarding on EC2 by domain name?

I have 2 dockers containers running on my EC2 instance:

  1. Docker1: Wordpress website running with PHP server mapped to port 8081 of EC2 instance.
  2. Docker2: Portal created on Angular running with NGINX mapped to port 8082 of EC2 instance.

I want to use the same EC2 instance for my domain and subdomain xyz.com and portal.xyz.com on the same port 80.

Ideally, if the request comes from xyz.com, it should redirect to Docker1 running on 8081 and if it is from portal.xyz.com, it should be redirected to Docker2 running on 8082.

Is it feasible and if yes, how? I do not want to spawn 2 EC2 instances for this and both have to be mapped to HTTP on port 80.

Upvotes: 0

Views: 1641

Answers (2)

Anoop Viswan
Anoop Viswan

Reputation: 41

I had done something similar on a VPS server, technically it should work on an ec2 instance as well.

  1. I created a new docker network 'proxy-network' (Note: You can do without creating a network and just proxy to localhost:8081 and localhost:8082. This is just cleaner)
  2. Launch all the application servers in that network with proper names (eg: wordpress, angular). Use --name in run command or conatiner_name in docker-compose.
  3. Launch a new nginx server map host port 80 and 443(if you need https to work). I used nginx:latest image. Created a new default.conf and replace /etc/nginx/conf.d/default.conf in container.

Sample proxy.conf should like this:

server {
  listen        80;
  server_name   domain1.com www.domain1.com;

  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass  http://wordpress;
  }
}
server {
  listen        80 default_server;
  server_name   domain2.com www.domain2.com;

  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass  http://angular;
  }
}

Once you update the alias records in domain registrar works like a charm. Hope it helps. Good luck.

Upvotes: 0

tvs
tvs

Reputation: 101

Using multiple load balancers and target groups can solve your problem. https://aws.amazon.com/about-aws/whats-new/2019/07/amazon-ecs-services-now-support-multiple-load-balancer-target-groups/

You can set up both load balancers to listen on HTTP and target your one ECS instance on different ports. After that, setting up the routes in Route53 will be straight forward.

Upvotes: 1

Related Questions