Docker与Singularity工作目录差异导致容器内脚本执行失败的问题咨询
test.sh & How to Fix It Without Modifying main.sh The Root Cause: Working Directory Differences Between Docker and Singularity
Let’s break down exactly why this error pops up. When you run sudo docker run -t myuser/mydocker:1.0 ./main.sh, Docker automatically uses the container’s defined working directory (either the WORKDIR set in your Dockerfile, or / if you didn’t specify one) as the starting point for your command. So ./main.sh runs from that directory, and when it calls ./test.sh, it looks in the same container directory where both scripts live—hence the successful output.
Singularity works differently here. When you run singularity exec -e docker://myuser/mydocker:1.0 /main.sh, it defaults to using your host system’s current working directory (not the container’s) unless you explicitly tell it otherwise. Even though you’re executing /main.sh via an absolute path, when that script tries to call ./test.sh, it’s searching for the file in your host’s current directory—not the container directory where test.sh is stored. That’s why you get the "No such file or directory" error.
Fixes That Don’t Require Changing main.sh
Here are two simple, script-friendly solutions:
1. Force Singularity to Use the Container’s Working Directory
Use the --pwd flag to set the container’s working directory to where your scripts are located (assuming they’re in /; adjust if your Dockerfile uses a different WORKDIR):
singularity exec -e --pwd / docker://myuser/mydocker:1.0 ./main.sh
This mimics Docker’s behavior, making Singularity run the command from the container’s root directory. Now ./test.sh will resolve to the correct location inside the container.
2. Wrap the Command to Switch Directories First
If you prefer not to use the --pwd flag, you can wrap the command to change to the container’s script directory before running main.sh:
singularity exec -e docker://myuser/mydocker:1.0 sh -c "cd / && ./main.sh"
This changes the working directory to / inside the container first, so the relative path to test.sh works just like it does with Docker.
Quick Side Note on the -e Flag
Just a heads-up: the -e flag clears host environment variables, which is fine for your current use case, but double-check it doesn’t interfere with any other dependencies your scripts might rely on down the line.
内容的提问来源于stack exchange,提问作者Giulia B.

