If a water heater pilot light does not stay lit, it is usually due to a faulty thermocouple. The thermocouple produces a heat-activated electrical current when it detects the pilot light, which keeps the gas valve open. When the thermocouple is defective or not functioning properly, it acts as though the water heater is off and cannot be lit.
When the pilot light is not turned or the thermocouple cannot detect it, the thermocouple shuts off the gas to the heater as a safety measure. One reason why the pilot light can be turned on and not remain lit is because the thermocouple is dirty or covered in soot. Gently sanding the thermocouple after turning off the gas and letting it cool can solve this problem.
Another reason why the thermocouple might act as though the light was off is because it is bent and the pilot flame isn't touching it. Bending it closer to the water heater pilot light will ensure that the thermocouple detects it and keeps the gas on.
A pilot light might also remain off if the pilot tube is dirty. Cleaning the pilot tube with a needle after it has cooled can resolve this issue. This can also happen if the thermocouple is damaged beyond repair and needs replacement.