My current configuration is as follows: I have two separate Angular apps on different Docker containers running on different ports, for example, 4200 and 4201. I access them both directly through their ports: www.myserver.com:4200 and www.myserver.com:4201. They are created using the following docker-compose config file:
version: '3.6'
services:
app1:
build:
context: ../app1
dockerfile: Dockerfile
command: bash -c "ng serve --host 0.0.0.0 --port 4200"
ports:
- "4200:4200"
app2:
build:
context: ../app2
dockerfile: Dockerfile
command: bash -c "ng serve --host 0.0.0.0 --port 4201"
ports:
- "4201:4201"
Now, I want to set up an nginx server to serve both apps on the same port, e.g. 80. What is the recommended way to change both apps so that they're served on different routes, e.g. www.myserver.com/app1 and www.myserver.com/app2, respectively? So far I have changed my docker-compose config file and nginx's dev.conf:
docker-compose.yml
nginx:
build:
context: ../nginx
dockerfile: Dockerfile
restart: always
ports:
- "80:80"
nginx/dev.conf
server {
listen 80;
location /app1 {
proxy_pass http://app1:4200;
proxy_redirect default;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
location /app2 {
proxy_pass http://app2:4201;
proxy_redirect default;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
}
Is it possible to do what I'm asking for? Would it be better to merge both Angular apps and route internally?
Thanks in advance.
Update: I ended up copying the contents from app2 into app1 and routing internally. I'll leave the question open in case anyone wants to suggest a different approach.
If you are deploying your angular apps this way in production using ng serve, I recommend you change that. Using ng serve should only be used in dev because the bundle size is huge and slows down initial load of the webpage.
Recommended way to deploy to production is using
This builds your app and puts all needed files in the /dist folder, possibly under a subdirectory depending on your angular version and settings. You should copy the contents of the /dist folder to your nginx container and configure nginx to point to the index.html file for the routes you set up.
For example, if you copy app1 to /usr/share/nginx/html/app1 and app2 to /usr/share/nginx/html/app2 your nginx config could be (given that the index.html files are in the root of /app1 and /app2 folders):
This is just a rough example, should work in theory but you most likely need to tweak it a little for it to work correctly in your setup.
Example nginx config if you want to point to the two dev containers: