问题
Instead of hardcoding the db_username and password, I want to define a env variable in docker. I am new to Docker, so some stuff I still need to learn more about.
Another question i want to ask is, if someone else want to run my container, like clone from github, they will have to set themselves the env variables to connect to db right? Create a .env and stuff like that..
config.php
<?php
define('DB_SERVER', getenv('DB_SERVER'));
define('DB_USERNAME', getenv('DB_USERNAME'));
define('DB_PASSWORD', getenv('DB_PASSWORD'));
define('DB_NAME', getenv('DB_NAME'));
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($link === false) {
die ("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
.env
DB_SERVER=db
DB_USERNAME=dbuser
DB_PASSWORD=dbpassword
DB_NAME=company
docker-compose.yml
db:
build: ./backend
restart: always
ports:
- "3306:3306"
volumes:
- /var/lib/mysql
environment:
- MYSQL_ROOT_PASSWORD=dbpassword
php:
build: ./frontend
ports:
- "80:80"
volumes:
- ./frontend:/var/www/html
environment:
- DB_SERVER=${DB_SERVER}
- DB_USERNAME=${DB_USERNAME}
- DB_PASSWORD=${DB_PASSWORD}
- DB_NAME=${DB_NAME}
env_file: ./.env
links:
- db
Dockerfile in ./frontend
FROM php:7.2-apache
RUN docker-php-ext-install mysqli
WORKDIR /var/www/html
COPY . /var/www/html/
Dockerfile in ./backend
FROM mysql:5.7
COPY ./demo.sql /docker-entrypoint-initdb.d
I don't know if the way it is right now, is getting the variables form the env file, when i run with the docker-compose up, and go to 192.168.99.100, my application is working, but i get
In the .yml file, i think i don't need the environment variables set, but i was testing if i could get that variables, directly put into the config.php, for someone who will run my container, only need to run "docker-compose up" and not set everything.
Warning: mysqli_connect(): (HY000/1045): Access denied for user 'dbuser'@'172.17.0.3' (using password: YES) in /var/www/html/config.php on line 8
I don't know how to solve that. So basically, it's two questions, why this error, and if I'm doing the environment variables right.
回答1:
I managed to get it to work, i don't really know what i changed, but basically i removed the environment:
from the php
container, and moved to the db
container, using the mysql image env variables from the dockerhub.
回答2:
I have solved this problem You need to add variable PHP_FPM_CLEAR_ENV=no
environment: - PHP_FPM_CLEAR_ENV=no
After that everything is ok!
来源:https://stackoverflow.com/questions/49969282/get-env-variables-from-env-or-dockerfile-docker-compose-yml-to-config-php-to-c