Exec vs Attach Commands

I conceptually understand the difference between docker exec and docker attach. But what are the practical differences for when to use exec and when to use attach? It seems I can make each behave like the other.

Hi,

Docker attach attaches to the process that runs in the container with PID 1. Where as Docker exec is used run a new process inside the container. Docker exec also gives you the feature to run the process as a different user and various other features.

Regards

@ranjandas I am a beginner to docker, while I am practicing I created container with jenkins image (which is used from dockers hub) and jenkins working normally. But when I am trying to connect to container with “attach” command it’s getting hanged. So I used “exec” command and able to connect to container. Not sure exactly why this is happend.

docker attach myjenkins — this command hanged

docker exec -it myjenkins /bin/bash — able to connect to container