What you need is to use the build pattern or the multistage features of docker
With that, you can use as many images as you need depending on your build process
TL;DR: You don't.
From inside of the container, you do not know which ports are exposed since exposing a port is only documentation visible in the image and container metadata. To detect which ports are published, you'd need to know the host IP, which can be difficult to lookup depending on your environment, and then you'd need to do something like a port ...
TL;DR: RUN performs the step during the image build, CMD is the default command when you start a container. If you define CMD and then start your container with a different command (e.g. docker run $my_image /bin/bash), you'll never see it run since you replaced your chmod command with an empty /bin/bash command.
The detailed explanation:
The RUN command ...