Because the Sun heats them. As a comet approaches the inner solar system, its ice turns directly from solid to gas — sublimation — and that escaping vapour drags loose dust with it.
Two forces then shape the debris into a tail. Sunlight pressure pushes the dust outward into a broad, curved tail, while the solar wind, a stream of charged particles, sweeps the ionised gas into a straighter tail pointing almost exactly away from the Sun.
The consequence is counterintuitive: a comet's tail does not trail behind its direction of travel but points away from the Sun, which means that on the outbound leg the tail actually leads the comet. Every close pass also strips material away, which is why comets eventually go quiet.