Both will be able to execute commands in container. Both could detach the container.
So what is the real difference between docker exec and docker attach?
When a container is started using /bin/bash then it becomes the containers PID 1 and docker attach is used to get inside PID 1 of a container. So docker attach < container-id > will take you inside the bash terminal as it's PID 1 as we mentioned while starting the container. Exiting out from the container will stop the container.
Whereas in docker exec command you can specify which shell you want to enter into. It will not take you to PID 1 of the container. It will create a new process for bash. docker exec -it < container-id > bash. Exiting out from the container will not stop the container.
You can also use nsenter to enter inside containers. nsenter -m -u -n -p -i -t < pid of container > You can find PID of container using: docker inspect < container-id > | grep PID
Note: If you have started your container with -d flag then exiting out of container will not stop the container,whether you use attach or exec to get inside.