i have a docker compose file in which there are several containers among which there are an api gateway and another one with an angularjs application (the website of this stack). The api gateway is concerned to call correct apis of several containers presents in the compose file. But i need to call the api gateway from the website (angular container) and
i would like to know what is the best practices for get the address of the api gateway container in order to call it from angular container (or from browser anyway..).
For the moment i working in local, so i specify
localhost:PortOfApiGateway/apis/...
and everything work fine, but obviously if try to connect from another host it not works...
Any suggestion?
Depending on your environment, I see several possible solutions.
1. You can have a config file in Angular
For example, Angular Cli provides 2 files: environment.ts and environment.prod.ts
The content of the file can be:
export const environment = {
production: false,
apiBaseUrl: 'http://localhost:3000'
};
and the equivalent for production can be the real DNS url
This is provided by Angular CLI but you can do the same without the CLI. The idea here is that the files are chosen at compile time.
2. Always use the same server
You can assume that the hostname will be the same as the one you got your Angular app from:
import { Location } from '@angular/common';
// Get the hostname
this.hostname = location.host;
if (this.hostname.indexOf(':') > 0) {
this.hostname = this.hostname.substr(0, this.hostname.indexOf(':'));
}
// Add a port or a subdomain to get the API url:
this.apiUrl = 'http://' + this.hostname + ':8080';
Variables in compose?
As you said in an earlier comment, the calls are made from the browser, so outside Docker. I don't see an easy way to put this information in the compose file. That said I would be interested to find out.
I hope it helps.
In your docker-compose file, you can make your containers join an existing network, which can be the default network. So, all you need to do is make sure that your containers join a network in which your angularjs container already is. Then, you can refer to your API container simply by the name you gave it in your docker-compose file (if you named it api, for example, ping api
will work). See Networking in Compose.