Publish: 2023-04-28 | Modify: 2023-04-28
Recently, when deploying services using Docker Compose, I encountered an issue with the $PWD variable in the docker-compose.yml file not working as expected.
Let's take a look at a snippet of the docker-compose.yml configuration file:
version: "3.9"
services:
xui:
image: enwaiax/x-ui
container_name: xui
volumes:
- $PWD/db/:/etc/x-ui/
- $PWD/cert/:/root/cert/
restart: unless-stopped
network_mode: host
I placed the docker-compose.yml file in the /data/apps/x-ui directory, and the configuration seems fine. I used the $PWD variable to represent the current directory. According to expectations, the absolute host mount paths should be:
When I ran the command sudo docker-compose up -d
to start the containers, there were no errors. However, the host mount paths did not work as expected and became:
It seems that the $PWD variable was either lost or not effective.
To analyze and solve this issue, I consulted ChatGPT, and the answer I received was:
It appears that the $PWD variable is not working as expected. This might be because the environment variables are not being passed to the docker-compose command when using sudo.
To resolve this issue, you can try the following methods:
version: "3.9"
services:
xui:
image: enwaiax/x-ui
container_name: xui
volumes:
- /data/apps/x-ui/db/:/etc/x-ui/
- /data/apps/x-ui/cert/:/root/cert/
restart: unless-stopped
network_mode: host
sudo -E docker-compose up -d
This will ensure that the $PWD variable remains effective when executing the docker-compose command. However, please note that using the -E option may have security risks as it passes all environment variables of the current user to the sudo command. Make sure you understand the potential risks and ensure that there are no sensitive variables in the current environment.
In addition to the above solutions, there is another option to use relative paths, such as:
version: "3.9"
services:
xui:
image: enwaiax/x-ui
container_name: xui
volumes:
- ./db/:/etc/x-ui/
- ./cert/:/root/cert/
restart: unless-stopped
network_mode: host
Then, navigate to the /data/apps/x-ui directory and execute sudo docker-compose -d
.
In conclusion, when using the sudo command, some environment variables may not be correctly passed to subsequent commands. To solve this issue, we can use the sudo -E parameter to preserve the environment variables or avoid relying on environment variables by using absolute or relative paths. This is especially important when a regular user operates Docker through the sudo command.
I come from China and I am a freelancer. I specialize in Linux operations, PHP, Golang, and front-end development. I have developed open-source projects such as Zdir, ImgURL, CCAA, and OneNav.