Variables in a Portainer stack look like normal Compose variables, but they do not always behave that way. The difference is worth knowing before you debug for an hour.
In the stack editor you can add environment variables in the UI, or load them with Load variables from .env file. In your Compose file you can reference them as ${VAR_NAME} and Portainer does not modify your file. For passing them into a container, Portainer documents this line:
services:
app:
env_file:
- stack.env
The docs say env_file: stack.env works on Docker standalone and Podman, but not on Docker Swarm. A related FAQ says that stack.env only sets variables under the environment field. It does not do substitution for things like port numbers or image versions, so those need ${...} in the Compose file itself.
The caveat is that your stack is not run from a folder on disk with a .env next to it. If a variable seems ignored, check which of the two mechanisms you are actually using.
My rule of thumb: if the value goes inside the container, use the environment mechanism. If the value changes the Compose file itself, use ${...} and set it in the Portainer variables.
Further reading: Add a stack, .env vs stack.env, On this site: migrating a stack in Portainer does not move its volumes, On this site: Detach from Git in Portainer only downloads the main compose file