如何修正`docker exec psql`的终端尺寸问题?
Ah, I’ve run into this exact issue before—using docker exec -tiu postgres some_db_container psql db_name is super convenient for skipping the username/password hunt, but that wonky TTY behavior is such a pain. Lines not wrapping, terminal size not being recognized, editing text turning into a mess? Let’s fix that.
Quick Solution
Just add the --env TERM=$TERM flag to pass your host terminal’s settings into the container:
docker exec -tiu postgres --env TERM=$TERM some_db_container psql db_name
Why This Happens
Here’s the breakdown: when you use -t to allocate a TTY, Docker doesn’t automatically pass along your host’s TERM environment variable. psql depends on this variable to know how to handle terminal formatting, line wrapping, and cursor placement. Without it, it falls back to a basic terminal type that doesn’t support these modern features—hence all the chaos.
Pro Tip: Save Yourself Typing
If you use this command a lot, add an alias to your shell config (like ~/.bashrc or ~/.zshrc):
alias docker-pg='docker exec -tiu postgres --env TERM=$TERM'
Now you can run it like this:
docker-pg some_db_container psql db_name
That should get your psql session working smoothly again, no more messy line edits or broken wrapping.
内容的提问来源于stack exchange,提问作者Altreus

