Merhaba
In general, it’s very safe. Of course all travel comes with a risk, but hundreds of solo travellers - male and female - do this every night without any problem.
Depending on the exact journey, you can often book into a female-only compartment, and you can book the whole compartment privately - although this is very expensive.
If you mention your route, somebody can give you advice on the types of accommodation available, and how much it costs for a private room.
But I would recommend a shared compartment. Fellow travellers will look after you, and of course you can always contact train staff if you ever feel unsafe.