Reputation: 98
I am using docker-compose with an image made by someone else and I would like to use environment variables to assign it dynamically
docker-compose.yml
version: "3.7"
services:
appfronted2:
image: trafex/alpine-nginx-php7
container_name: fronted2
ports:
- "80:8080"
volumes:
- ./fronted2:/var/www/html
environment:
- HOST_BACKEND=172.99.0.11
- PORT_BACKEND=4000
networks:
tesis:
ipv4_address: 172.99.0.13
and this is my javascript where I would like to get the variables but I can't get those variables
api.js
const HOST = process.env.HOST_BACKEND || "127.0.0.1"
const PORT = process.env.PORT_BACKEND || "4000"
const URL_API = `http://${HOST}:${PORT}/api`
Upvotes: 0
Views: 5313
Reputation: 346
You are using nginx web server container to serve your html and JS files. The web server serves these files to browser as they are. This is different from using npm start
where Node engine serves the HTML and JS files dynamically.
When your JS file runs on client browser, there's no variable called process.env.
Going over comments for following issue in Create React app might help you understand more:
https://github.com/facebook/create-react-app/issues/2353
If you don't have more environment variables, simplest solution would be to use window.location.hostname
and prepare or select the API url accordingly.
app-config.js
let backendHost;
const hostname = window && window.location && window.location.hostname;
if(hostname === 'whatsgoodonmenu.com') {
backendHost = 'https://api.whatsgoodonmenu.com';
} else {
backendHost = 'http://localhost:8080';
}
export const API_ROOT = `${backendHost}`;
Using in component
import React from "react"
import {API_ROOT} from './app-config'
export default class UserCount extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
};
}
componentDidMount() {
fetch(`${API_ROOT}/count`)
.then(response => response.json())
.then(data => this.setState({ data }));
}
render(){
return(
<label>Total visits: {this.state.data}</label>
);
}
}
Upvotes: 2