Reputation: 2203
I have enviroment.prod.ts file in my Angular app
export const environment = {
backendUrl: '127.0.0.1:3000',
};
And this is a part of docker-compose.prod.yml:
....
environment:
- ENV_BACKEND_URI=127.0.0.1:3000
....
How can I set backendUrl
using ENV_BACKEND_URI
from docker-compose.prod.yml?
I want something like that:
export const environment = {
backendUrl: '${ENV_BACKEND_URI}',
};
Is this posible?
Upvotes: 7
Views: 8775
Reputation: 955
Yes - it is possible, even though Angular runs on the client's environment, it still runs build steps on the environment it is deployed on.
Generally the envsubst
program can be used to feed environment variables into a file. So with your above example of an environment.ts
file:
export const environment = {
backendUrl: '${ENV_BACKEND_URI}',
};
If we were to name it src/environments/environment.template.ts
, the command
envsubst < src/environments/environment.template.ts > src/environments/environment.ts
will produce an `environments.ts file as desired, with ${ENV_BACKEND_URI} replaced as per environment variables.
Don't forget to have your Dockerfile install it in your docker image (using the appropriate package installer method listed here)
This command needs to be run as docker-compose up
starts the container, so that it will have access to the environment variables injected into the container spawned by docker-compose.
This can be acheived in a couple of ways:
ng serve
usually command used to start Angular (either as CMD
in your Dockerfile, or command
in the docker-compose.yml
dockerfile withenvsubst < src/environments/environment.template.ts > src/environments/environment.ts && ng serve
or
ng serve
run npm run start
as the docker command. This will run the start
script in your package.json
(which by default is ng serve
), but will run anything in a "prestart" script first. So edit package.json
to contain:"scripts": {
"ng": "ng",
"prestart": "envsubst < src/environments/environment.template.ts > src/environments/environment.ts",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
Upvotes: 9
Reputation: 982
Well from where should your system environment content comes?
Your angular app get's shipped to the user via whatever webserver, there is no node.js process or something else which could offer you a server environment variable.
consider the environment.ts in angular as a built time one-way collection of flags.
The only way to change things afterwards the app is shipped goes to api calls.
So setup a secure way to maybe request GET /api/config maybe with a one way startup token or whatever could be secure.
Upvotes: 0